Skip to main content
edited tags
Link
avpaderno
  • 97.9k
  • 15
  • 164
  • 284
Notice removed Draw attention by shasi kanth
Bounty Ended with Naveen Valecha's answer chosen by shasi kanth
Tweeted twitter.com/#!/StackDrupal/status/531682188459143168
Notice added Draw attention by shasi kanth
Bounty Started worth 50 reputation by shasi kanth
Source Link
shasi kanth
  • 569
  • 2
  • 11
  • 23

Populate multiselect options onchange of dropdown using AJAX

I have created a content type (Geological Locations) with 2 fields, Country and States.

The Country field is a select box, and States field is a multiselect. So if i select a Country, the States multiselect should be populated based on the selected Country using AJAX.

In my custom module, i used node_form_alter() to customize the node creation form.

I have tried the below code, but it is not working as expected.

function demo_form_geological_locations_node_form_alter(&$form, &$form_state, $form_id) {
    $form['additional_settings']['#access'] = false;
    $form['field_country']['und']['#options'] = array(''=>'Select', 'india'=>'India', 'usa'=>'USA');
    $selected = isset($form_state['values']['field_country']) ? $form_state['values']['field_country'] : '';
    
    $form['field_country']['und']['#ajax'] = array(
          'callback' => 'ajax_states_callback',
          'wrapper' => 'states-wrapper',
    );
    
    $form['field_states']['#prefix'] = '<div id="states-wrapper">';
    $form['field_states']['#suffix'] = '</div>';
    $form['field_states']['und']['#options'] = ajax_get_state_options($selected);
    
    return $form;
}

function ajax_states_callback($form, $form_state) {
    return $form['field_states'];
}

function ajax_get_state_options($key = '') {
    $options = array(
        t('usa') => drupal_map_assoc(
          array(
            t('Florida'),
            t('Georgia'),
            t('Atlanta')
          )
        ),
        t('india') => drupal_map_assoc(
          array(
            t('Maharashtra'),
            t('Gujarat'),
            t('Karnataka')
          )
        )
    );
    
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

Can anyone tell me where i am going wrong? I am expecting the output like below screenshot, when i select the Country "India":

enter image description here