Skip to main content

Using State API in Drupal Forms (Custom Conditional Fields)

Submitted by amitsedai on
The following is a snippet on how to enable fields to appear and/or disappear based on the state of other fields. <?php /** * Modifications for including State API functionalities. The idea is to hide the fields field_referme_industry * and field_referme_major_skills, based on the value of another field. * The functionality can be implemented during the after_build phase */ function jc_form_alter(&$form, &$form_state, $form_id) { //drupal_set_message("Form Id is: $form_id "); if($form_id == 'referme_node_form') { $form['field_referme_industry']['#after_build'] = array('jc_referme_ctc_after_build'); $form['field_referme_major_skills']['#after_build'] = array('jc_referme_ctc_after_build'); } } /** * Hide the industry and Major Skills when CTC is mentioned as Fresher */ function jc_referme_ctc_after_build($form_entity, &$form_state) { $form_entity['#states'] = array( 'invisible' => array( ':input[name="field_referme_current_ctc[und]"]' => array('value' => t('Fresher')), ), ); return $form_entity; } ?> States API also allows providing multiple values for triggering <?php '#states' => array( 'visible' => array( ':input[name="field_star_rating"]' => array( array('value' => t('5')), array('value' => t('4')) ), ), ), ?> -- https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_states/7 http://evolvingweb.ca/story/extending-form-api-states-regular-expressions