On this page
Select (or other)
The Select (or other) module provides a Forms API element, and integrates it with the Fields API. However, developers and coders can make use of this element in a custom form for any purpose. This page outlines the developer usage and available attributes.
Example developer usage in Forms API
<?php
$form['my_field'] = array(
'#type' => 'select_or_other_select',
'#title' => t('Choose an option'),
'#default_value' => array('value_1'),
'#options' => array(
'value_1' => t('One'),
'value_2' => t('Two'),
'value_3' => t('Three'),
),
'#other_option' => t('Other (please type a value)'), // Text to show as 'other' option (optional, defaults to "- Other -")
'#required' => TRUE,
'#multiple' => TRUE,
'#other_unknown_defaults' => 'other', // If the #default_value is not a valid choice in #options, what should we do? Possible values 'append', 'ignore', 'other' (if 'other' specified you can also override #other_delimiter).
'#other_delimiter' => ', ', // Delimiter string to delimit multiple 'other' values into the 'other' textfield. If this is FALSE only the last value will be used.
'#select_type' => 'select', // Defaults to 'select'. Can also be 'radios' or 'checkboxes'.
);
?>
The #properties you give the element that are recognised as FAPI select properties will be automatically assigned to the Select element. Also any #properties assigned as #select_property or #other_property will be passed down to the corresponding form element. For example, to use ajax with the select_or_other element, use the property #select_ajax or #other_ajax, instead of simply #ajax.
Note that in the form validate/submit function, $form_state->getValue('my_field') always returns an array (which is always a one-element array if #multiple is FALSE), unlike regular 'select' type elements.
Drupal 7 example
<?php
$form['my_field'] = array(
'#type' => 'select_or_other',
'#title' => t('Choose an option'),
'#default_value' => array('value_1'),
'#options' => array(
'value_1' => t('One'),
'value_2' => t('Two'),
'value_3' => t('Three'),
),
'#other' => t('Other (please type a value)'), // Text to show as 'other' option
'#required' => TRUE,
'#multiple' => TRUE,
'#other_unknown_defaults' => 'other', // If the #default_value is not a valid choice in #options, what should we do? Possible values 'append', 'ignore', 'other' (if 'other' specified you can also override #other_delimiter).
'#other_delimiter' => ', ', // Delimiter string to delimit multiple 'other' values into the 'other' textfield. If this is FALSE only the last value will be used.
'#select_type' => 'select', // Defaults to 'select'. Can also be 'radios' or 'checkboxes'.
);
?>
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion