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":