It's probably working as designed but not always as logical to me. When checkbox B will get checked when checkbox A is checked, it doesn't matter if it has a default value 'checked'. It will always be overridden by javascript and be unchecked at page load because checkbox A is unchecked.
Example:
$form['checkbox_a'] = array(
'#type' => 'checkbox',
'#title' => t('Checkbox A'),
);
$form['checkbox_b'] = array(
'#type' => 'checkbox',
'#title' => t('Checkbox B'),
'#default_value' => 1, // This one gets overridden at page load due to the #states.
'#states' => array(
'checked' => array(
':input[name="checkbox_a"]' => array('checked' => TRUE),
),
),
);
As you can see, 'checkbox B' has a default value of 1 (checked), but it will never be checked when the page gets loaded (well, for a millisecond it does) because it's depending on 'checkbox A' through javascript. Though, 'checkbox B' can be manually clicked and checked independently from 'checkbox A', which is good. But at page load, the #states override the default value.
My question: is there a way in the form API to avoid this, so the default value doesn't get undone. Apart from writing the javascript ourselves because that would make the form states useless.
| Comment | File | Size | Author |
|---|---|---|---|
| #5 | drupal_checkboxes2.gif | 1.45 MB | jimafisk |
Comments
Comment #1
fernly commentedComment #2
fernly commentedComment #3
cilefen commentedDoes the 'touched' state work? If it did, you could try something like:
Comment #4
fernly commentedUnfortunately not working, but thanks for the suggestion.
Comment #5
jimafisk commentedI ran into this issue as well on an Entity Reference field (taxonomy for Neighborhoods in my case). I was able to get around it with the addition of an 'unchecked' state as shown below.
For some additional context about why the code is written the way it is below, I also ran into a problem where the the 'checked' state wasn't being applied to the correct HTML element (see https://www.drupal.org/node/994360#comment-5860156), so I needed to loop through the checkbox options individually and apply the state to each option that way.
The trick is to tell Drupal to uncheck the boxes only if they're already unchecked. Since the default values load as checked, it shouldn't uncheck them. Strangely from there, the controlling checkbox can enable/disable all boxes, which is exactly what I wanted (see attached gif to see it in action).