FormIt.Handling Selects, Checkboxes and Radios

Skip to end of metadata
Go to start of metadata

Handling Selects, Checkboxes and Radios

While FormIt can handle any type of field, special directions are required for selects, radios and checkboxes due to their value nature.

Handling Select Fields

FormIt provides a utility snippet, called FormItIsSelected, which can be used as an Output Filter to handle the selected="selected" part of the option. Example:

<select name="color">
   <option value="blue" [[!+fi.color:FormItIsSelected=`blue`]] >Blue</option>
   <option value="red" [[!+fi.color:FormItIsSelected=`red`]] >Red</option>
   <option value="green" [[!+fi.color:FormItIsSelected=`green`]] >Green</option>

   <!-- This would also work -->
   <option value="yellow" [[!+fi.color:is=`yellow`:then=`selected`]]>Yellow</option>
</select>

This will automatically handle the "selected" part of the option field, persisting it through validation and error handling.

Handling Checkboxes and Radios

Handling checkboxes and radios is very similar to handling selects, with the only difference being how you handle "required" validation on them. FormIt provides a FormItIsChecked assistance OutputFilter, similar to FormItIsSelected, for handling value persistence.

This example will handle checkboxes, persisting their values:

<label>Color: [[!+fi.error.color]]</label>
<input type="checkbox" name="color[]" value="blue" [[!+fi.color:FormItIsChecked=`blue`]] > Blue 
<input type="checkbox" name="color[]" value="red" [[!+fi.color:FormItIsChecked=`red`]] > Red 
<input type="checkbox" name="color[]" value="green" [[!+fi.color:FormItIsChecked=`green`]] > Green 

Note that the [] is stripped when setting the "fi.error.color" placeholder.

Handling Required on Checkboxes

Since HTML does not send a value if a checkbox is not checked, handling the "required" validation on a checkbox can be tricky. You'll need to add a "hidden" field before so that at least an empty value is sent:

[[!FormIt? &validate=`color:required`]]
...
<label>Color: [[!+fi.error.color]]</label>
<input type="hidden" name="color[]" value="" />
<input type="checkbox" name="color[]" value="blue" [[!+fi.color:FormItIsChecked=`blue`]] > Blue 
<input type="checkbox" name="color[]" value="red" [[!+fi.color:FormItIsChecked=`red`]] > Red 
<input type="checkbox" name="color[]" value="green" [[!+fi.color:FormItIsChecked=`green`]] > Green 

This will successfully check to make sure at least one checkbox was selected when submitting the form.

See Also

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.