Jump to content

Developer Documentation

Using field toggle functionality in forms

What are toggles?

Frequently in form design you'll want to show or hide groups of fields depending on the values of other fields. For example, assume you have a Yes/No field that enables some feature, and some other fields that customize how the feature works. When the user checks 'No' to disable the feature, you can hide the other fields using toggles (and show them automatically when 'Yes' is checked). By doing so, you simplify your form design, and make it easier for users to understand each field they see, with the correct context.

IPS4 has built-in support for this kind of behavior on forms using the toggles functionality. It's automatic - you simply specify the relevant element IDs when building your form.

 

Using form toggles

The options available for this depends on the field type. For example, YesNo has two options: togglesOn (which controls which elements to show when the setting is set to "Yes") and togglesOff (which controls which elements to show when the setting is set to "No"). Select has one toggles option which accepts an array, specifying which elements should show for each of the available values. Number has an unlimitedToggles which specifies which elements show when the "Unlimited" checkbox is checked and a unlimitedToggleOn option to reverse that behavior to when the checkbox is unchecked. For more information, see the source code for each element type in the system/Helpers/Form directory.

All toggle options accept an array of HTML element IDs that should be toggled. For example, to toggle an element with the ID 'myElement' from a YesNo field, you'd do:

$form->add( new \IPS\Helpers\Form\YesNo( 'yes_no_field', NULL, TRUE, array( 'togglesOn' => array( 'myElement' ) ) ) ); 

Note that if you plan to toggle other form elements, you will need to manually specify an element ID (the last parameter of the field constructor). For example, to have our YesNo field toggle a text field, we must also specify an ID on the text field like so:

$form->add( new \IPS\Helpers\Form\YesNo( 'yes_no_field', NULL, TRUE, array( 'togglesOn' => array( 'text_field_container' ) ) ) ); 
$form->add( new \IPS\Helpers\Form\Text( 'text_field', NULL, TRUE, array(), NULL, NULL, NULL, 'text_field_container' ) );

 


  Report Document


×
×
  • Create New...