How to create dependent drop down in custom form using Ahah module in Drupal?

Here I am explaining step by step, how you can create dependent drop down.

Please go through the code and read the comment.

function example_ahah_form( $form_state ) {
  $form = array();
 
  // this is standard method for register ahah helper for current form
  ahah_helper_register($form, $form_state);
 
  // provide default option for select one
  $select1_selected = 1;
 
  // $form_state['storage'], contains ahah submitted values
  if ( isset($form_state['storage']['dependent_select']['select1']) ) {
 
     // get 'select1' selected option
    $select1_selected = $form_state['storage']['dependent_select']['select1'] ;
  }
 
  // build select2 options depending upon select1
  if ( $select1_selected == 1 ) {
     $select2_options['11'] = 'option1 [select1]';
     $select2_options['12'] = 'option2 [select1]';
  }
  else if ( $select1_selected == 2 ) {
    $select2_options['21'] = 'option1 [select2]';
    $select2_options['22'] = 'option2 [select2]';
  }
  $form['dependent_select']['select1'] =
    array(
      '#type' => 'select',
      '#title' => t('Select 1'),
      '#options' => array( 1=> 'option1', 2 => 'option2'),
      '#default_value' => array( $select1_selected ),
     
      // specify ahah event
      '#ahah' => array(
      'event' => 'change', // this is onchange event of select
      'path' => ahah_helper_path(array('dependent_select')),
     
      // provide temporary path
      // no need to register it through hook_menu
      'wrapper' => 'dependent-select-wrapper',
     
      // provide the wrapper of element
      // here we have given the id of fieldset
     ),
   );
    $form['dependent_select']['select2'] =
    array(
      '#type' => 'select',
      '#title' => t('Select 2'),
      '#options' => $select2_options // set dynamic options
    );
    $form['submit'] =
    array( '#type' => 'submit',
      '#value' => t('Save')
      );
  return $form;
}

No comments:

Post a Comment