Multiple conditions for dynamic forms in Drupal 7
James Williams
Here's a quick follow-up to my original post on Dynamic forms in Drupal 7, as a reply to Wappie08, who asked me about combining conditions in the #states
array to add increased control over the display of your form elements. The question:
Hi James Williams, I read your blog post about d7 & #states in the FAPI which is really cool! One problem is that the information is also listed in the drupal.org example module, I was missing one important extra hint: how can you make an IF statement?
I mean:
IF field_1 is '1' or '2'
and also:
IF field_1 is '1' OR field_2 is '7'
If can can enlighten me maybe that's also an interesting addition on your article or the rest of the drupal community :)
You can combine #states
conditions together, AND-ing them with what is currently available in core:
$element['new_window'] = array(
'#type' => 'checkbox',
'#title' => t('Open link in new window'),
'#default_value' => $settings['new_window'],
'#states' => array(
'visible' => array( // action to take.
':input[name="fields[field_my_field][settings_edit_form][settings][make_link]"]' // element to evaluate condition on
=> array('checked' => TRUE), // FIRST condition
':input[name="fields[field_my_field][settings_edit_form][settings][make_link]"]' // element to evaluate condition on
=> array('enabled' => TRUE), // SECOND condition
),
),
);
So in the case above, our new_window
element is only made visible if the two conditions are BOTH true. We've just simply added a second condition to the array of conditions. Unfortunately, conditions cannot be OR-ed (or XOR-ed) by just using Drupal core yet. See http://drupal.org/node/1106388#comment-4269336. Some work has been done and is continuing on getting this in for Drupal 8, and hopefully it will be backported for D7 eventually. So I would recommend that you take a look at these two issues and perhaps use a patch from them:
1) FAPI #states: Fix conditionals to allow OR and XOR constructions
2) #states selector matching multiple checkboxes does not trigger state
If you try this, you could help move the issues along by doing some extensive testing and posting up testing reports. Then we might all get to play with multiple conditions! You may find that the Conditional Fields module is worth a look for this, though I haven't tried it myself. Let me know how you get on, this is now pushing out at the boundaries of what Drupal can do!