Drupal 7 FAPI - Using form states for conditional field display

April 8, 2012 | 0 Comments | Submitted by selvam

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 ).

  1.     $form['field_user_discount']['#states'] = array(
  2.       'disabled' => array(
  3.         ':input[name="field_user_group"]' => array('value' => 'gold'),
  4.       ),
  5.  
  6.       'enabled' => array(
  7.         ':input[name="field_user_group"]' => array('value' => 'silver'),
  8.       ),
  9.  
  10.       'invisible' => array(
  11.         ':input[name="field_user_group"]' => array('value' => 'bronze'),
  12.       )

 

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,

  1. '#states' => array(
  2.     'visible' => array(
  3.       ':input[name="field_checkbox_name"]' => array('checked' => TRUE),
  4.     ),

 



Comments