Tip: Determine the number of toggled switch fields

This tip explores requiring users to flick a certain number of switch fields before being allowed to proceed.

Sometimes, you need users to select a fixed number of options in the form of switch fields. If the user toggles the wrong number of options, an error message should be displayed and the user prevented from moving on the next screen:

In the app above, exactly three fields must be toggled on — no more, no less.

To accomplish this, we need the FILTER and SIZE functions. This formula is associated with the Visible property of the text box displaying the error message:

SIZE(FILTER(MainScreen.SwitchFields, MainScreen.SwitchFields)) <> 3SIZE(FILTER(MainScreen,SwitchFields; MainScreen,SwitchFields)) <> 3

Let’s unpack the formula one part at a time.

FILTER(MainScreen.SwitchFields, MainScreen.SwitchFields)FILTER(MainScreen,SwitchFields; MainScreen,SwitchFields) filters the switch fields of MainScreen, returning an array holding only those switch fields that have been toggled to their on positions.

The first parameter is the array to filter, MainScreen.SwitchFieldsMainScreen,SwitchFields, which unsurprisingly consists of all switch fields of MainScreen.

The second parameter is a logical array of the same size as the first array, determining which elements to keep. FILTER({ 1, 2 }, { FALSE, TRUE })FILTER({ 1; 2 }; { FALSE; TRUE }), for instance, returns { 2 }{ 2 }.

When MainScreen.SwitchFieldsMainScreen,SwitchFields is provided as the second parameter, Calcapp accesses the Value property of every switch field, meaning that MainScreen.SwitchFieldsMainScreen,SwitchFields and MainScreen.SwitchFields.ValueMainScreen,SwitchFields,Value are equivalent in this context.

The end result is that an array consisting of only the switch fields whose values are TRUE are returned from FILTER.

Next, SIZE returns the number of elements of the array returned from FILTER. In other words, SIZE returns the number of switch fields that have been toggled on.

Finally, remember that the overall formula is associated with the Visible property of the text box displaying the error message. As the error message should be shown if not exactly three switch fields have been toggled on, <> is used:

SIZE(FILTER(MainScreen.SwitchFields, MainScreen.SwitchFields)) <> 3SIZE(FILTER(MainScreen,SwitchFields; MainScreen,SwitchFields)) <> 3

To prevent users from moving on to the next screen if not exactly three switch fields have been toggled on, the NextScreenAvailable property of the form screen should be used.

« Bug report: Formulas now work better Tip: Display only selected screens »