I am new in drupal and I am working on one form where I need to create Country, State and city interdependent,hierarchical ajax dropdowns. So far I could achieve country and state dropdown but while making city dynamic on change of state is not working. It calls same callback and wrapper which I used for country even if I kept them separate. Please check below code

$form['account']['country_id'] = array(
    "#type" => "select",
    "#title" => t("Select your country."),
    "#options" => $countryArray,
    '#ajax' => array(
        'callback' =>'my_module_ajax_dropdown_state',
        'wrapper' => 'state-wrapper',
    '#id' => 'country',
    '#required' => true

 if (isset($form_state['values']['state_id'])) {
    // Pre-populate options for city dropdown list if province id is set
    $cityOptions = _load_city($form_state['values']['state_id']);

// Options for city dropdown list
$stateOptions = array('- Select state -');
if (isset($form_state['values']['country_id'])) {
    // Pre-populate options for city dropdown list if province id is set
    $stateOptions = _load_state($form_state['values']['country_id']);

$form['account']['state_id'] = array(
    "#type" => "select",
    "#title" => t("Select your county/State."),
    '#prefix' => '<div id="state-wrapper">',
    '#suffix' => '</div>',
    "#options" => $stateOptions,
    "#ajax" => array(
        'callback' =>'my_module_ajax_dropdown_city',
        'wrapper' => 'city-wrapper',
    '#default_value' => '--Select State--',
    '#id' => 'state',
    '#required' => true

$form['account']['city'] = array(
    "#type" => "textfield",
    "#title" => t("Enter your city."),
    '#id' => 'city',
    '#prefix' => '<div id="city-wrapper">',
    '#suffix' => '</div>',
    '#required' => true,
    '#default_value' => $account->city

These are my callback functions which are returning form element

function my_module_ajax_dropdown_state($form, $form_state){
  return $form['account']['state_id'];

function my_module_ajax_dropdown_city($form, $form_state){
 return $form['account']['city_id'];

I am trying to figure it out but no success yet. Please help me.



I was facing the similar issue in my drupal site. The other issue was the performance especially for IE where it took too much time in rendering the new item.

After some experiments, I made the following module that can help in making three hierarchical dropdown for country state and city. Its developed in a generic way that it can be used for n number of dependent dropdowns and can be used for other dependent data as well.


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