When I create a standard select box using the Drupal 7 form API, the first value (also the one selected on a fresh 'blank form') is <option selected="selected" value="">- Select -</option>
. This value is not specified in the form definition and I am doing no form altering. (This is fine)
However, when I create a second select box that depends on the first using #states
, it does not have any such default value. For complex forms with multiple dependencies this inconsistency is a problem.
An example form definition is as follows:
function sb_quickquote_test_form($form, &$form_state, $post=array()) {
$fields['first_select'] = array(
'#type' => 'select',
'#title' => 'First select box',
'#options' => Array('First', 'Second', 'Third'),
'#required' => TRUE,
);
$fields['dependent_delect'] = array(
'#type' => 'select',
'#title' => 'Dependent select box',
'#options' => Array('Something', 'Another thing', 'Something else', 'Final thing'),
'#states' => Array(
'visible' => Array('select[name=first_select]' => array('value' => '2')),
'required' => Array('select[name=first_select]' => array('value' => '2')),
),
);
$fields['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $fields;
}
In this simple example, we have 2 select boxes and a submit button. The two select boxes are displayed as:
______________ ________________
| - Select - |v| | Something |v|
`--------------' `----------------'
| - Select - | | Something | <- no empty option
| First | | Another thing |
| Second | | Something else |
| Third | | Final thing |
-------------- ----------------
(Because of the #states
setting, the second select box only appears when the first select box has "Third" selected)
This inconsistency is causing problems in a situation where we are generating complex dynamic forms with inter-dependant fields.
Does anyone have any idea why the fields are being given inconsistent options and what the best approach is to work around the problem?