Drupal states API snippets (conditional fields)

Here are some examples of using Drupal's states API. It shows the use of OR and XOR (which only work with jQuery 1.8 or above, apparently). More examples can be found in the examples project in the form example module.

Instead of using the #states API, there is also the conditional fields module and the field conditional states modules.

<?php
/**
 *  Implements hook_form_alter().
 */
function examplemodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    // Shows target field if control field is in a particular state.
    case 'exampleform01':
      $form['field_example_target']['#states'] = array(
        'visible' => array(
          ':input[name="field_example_control[und]"]' => array('value' => 'example_value'),
        ),
      );
      break;
    // Shows target field if two control fields are in a particular state.
    case 'exampleform02':
      $form['field_example_target']['#states'] = array(
        'visible' => array(
          ':input[name="field_example_control[und]"]' => array('value' => 'example_value'),
          '#edit-title' => array('value' => 'example_value2'),
        ),
      );
      break;
    // Shows target field if at least one control field is in a particular
    // state. Requires jQuery >= 1.8.
    case 'exampleform03':
      $form['field_example_target']['#states'] = array(
        'visible' => array(
          array(
            array(':input[name="field_example_control[und]"]' => array('value' => 'example_value')),
            'or',
            array('#edit-title' => array('value' => 'example_value2')),
          ),
        ),
      );
      break;
    // Shows target field if one and only one control field is in a particular
    // state. Requires jQuery >= 1.8.
    case 'exampleform04':
      $form['field_example_target']['#states'] = array(
        'visible' => array(
          array(
            array(':input[name="field_example_control[und]"]' => array('value' => 'example_value')),
            'xor',
            array('#edit-title' => array('value' => 'example_value2')),
          ),
        ),
      );
      break;
  }
}
?>

Tags

Internal References

External References

Article Type

General