1

I am using Drupal 7. I have created two form (FAPI) fields of type select , State and District. The district field should contain the dynamic options based on the state selected.

State field:

 $form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
  ),
  '#options' => $options,
  '#required' => '1',
  );

District field:

 $form['district'] = array(
  '#title' => t('Name of your District:') ,
  '#type' => 'select',
  '#default_value' => array(
  ),
  '#options' => district_list($form_state['values']['state']), // district_list is the function which will return the list of district based on name of state passed.
  '#required' => '1',
  );

The above code doesn't work, is there anything I am missing ?

  • Yes - the code to make your form element dynamic. What led you to believe what you've got would make an AJAX-enabled, dynamic select list group? I ask because whatever documentation, tutorial, example or question/answer you're following is way off and needs to be corrected – Clive Jun 30 '14 at 10:27
1

You need to use the #ajax property in your State select list, with a callback function that returns the district element. So something like this:

$form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
   ),
  '#options' => $options,
  '#required' => '1',
  '#ajax' => array(
    'callback' => 'MY_MODULE_state_ajax_callback',
    'wrapper' => 'edit-district',
 );

then create a callback called MY_MODULE_state_ajax_callback($form, &$form_state) and within the function,

MY_MODULE_state_ajax_callback($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    return $form['district'];
}

It may be slightly more complicated than this, based on your use-case, but this is the meat of it.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.