Conditional Field Drupal Form API

  0 comments Share with:

Sometime you need to create conditional Field for displaying dynamic content to your user - using Drupal's form states(conditional fields). Its a Drupal Form API and quite easy to display any form content conditionaly. You genearally do this by using simple jQuery to show/hide field based on the user selection choice. Here we are going to implement same thing but by using Drupal Form API.

So, Lets create a simple Drupal form which contain three fields.

function create_conditional_form() { $form['Name'] = array( '#type' => 'textfield', '#title' => t('Name'), '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); $form['Qualification'] = array( '#type' => 'select', '#title' => t('Qualification'), '#required' => TRUE, '#options' => array( 0 => t('Select'), 1 => t('Graduate'), 2 => t('Post Graduate'), ), '#default_value' => 0, '#description' => t('Select higher degree you have.'), ); $form['Work_Experience'] = array( '#type' => 'radios', '#title' => t('Work Experience'), '#required' => TRUE, '#options' => array('Fresher' => t('Fresher'), 'experience' => t('Experience')), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), ); return $form; }

Once you complete the above code, you will get a Drupal Form as

Drupal form

Now we are going to add another field which will be visible only after selection of work experience as "experience". For this we'll add "satates" attribute to field which will only display on proper selection.

$form['Year'] = array( '#type' => 'select', '#title' => t('Year'), '#states' => array( 'visible' => array( ':input[name="Work_Experience"]' => array('value' => 'experience'), ), ), '#options' => array( 0 => t('Year'), 1 => t(' t('<=2 year'), 3 => t('<=3 year'), 4 => t('3+ year'), 5 => t('4+ year'), 6 => t('5+ year'), ), '#default_value' => 0, '#description' => t('How much year of Experience you have.'), );

Drupal conditional form

Add new comment