Drupal 7 FAPI - Using form states for conditional field display
Submitted by selvam on Sun, 04/08/2012 - 17:14
Introduction
Drupal introduced a new form element attribute called 'states'. This adds Javascript to change the state of an element based on another element. The state denotes the property of a form element, for eg. visible, enabled and so on.
Common states
- enabled
- disabled
- required
- optional
- visible
- invisible
- checked
- unchecked
- expanded
- collapsed
Example
Let us assume that we have a field so called as 'field_user_group' ( list type ) in some form with values gold, silver, bronze and we want to alter the display of field 'field_user_discount' ( text ).
-
$form['field_user_discount']['#states'] = array(
-
'disabled' => array(
-
':input[name="field_user_group"]' => array('value' => 'gold'),
-
),
-
-
'enabled' => array(
-
':input[name="field_user_group"]' => array('value' => 'silver'),
-
),
-
-
'invisible' => array(
-
':input[name="field_user_group"]' => array('value' => 'bronze'),
-
)
The discount field will be disabled when field_user_group has a value of 'gold', enabled when the value is 'silver' and invisible when value is 'bronze'.
The value might involve even checkbox status like below,
-
'#states' => array(
-
'visible' => array(
-
':input[name="field_checkbox_name"]' => array('checked' => TRUE),
-
),
Related blogs
- Drupal 7 - Creating editable table with Form API
- How to add AJAX validation to a specific field in node form
- Drupal Form API - Overriding required field asterisk
- Drupal 7 - Exposing pseudo field in view from custom table
- Add Placeholders to Captcha input field
- How to redirect an user after logging into a drupal 7 site?

