using hook_form_alter and custom form elements below
$form['get-quotes-shipping']['country'] = array(
'#type' => 'select',
'#options' => array('_none' => '- None -') + country_get_list(),
'#multiple' => FALSE,
'#weight' => 3,
'#title'=>t('Country'),
'#default_value' => (isset($_SESSION['selected_country'])) ? $_SESSION['selected_country'] : '_none',
'#ajax' => array(
'event' => 'change',
'wrapper' => 'squadron-wrapper',
'callback' => '_get_state_field',
'method' => 'replace',
),
);
$form['get-quotes-shipping2']['actions']['get_quotes'] = array(
'#type' =>'submit',
'#value' => 'Get Quotes',
'#submit' => array('custom_changes_get_quotes_submit'),
'#validate' => array('custom_changes_get_quotes_validate'),
'#weight' => 1,
);
$squadron_options = array();
if (isset($_SESSION['selected_country'])) {
module_load_include('inc', 'location');
$states = location_get_provinces($_SESSION['selected_country']);
$squadron_options = $states;
}
$form['get-quotes-shipping0']['states']['#type'] = 'select';
$form['get-quotes-shipping0']['states']['#title'] = t('State/Province');
$form['get-quotes-shipping0']['states']['#prefix'] = '<div id="squadron-wrapper">';
$form['get-quotes-shipping0']['states']['#suffix'] = '</div>';
$form['get-quotes-shipping0']['states']['#options'] = array('_none' => '- None -') + $squadron_options;
if (isset($squadron_options[0])) {
$form['get-quotes-shipping0']['states']['#default_value'] = $squadron_options[0];
}
Callback function as given below.
function _get_state_field(&$form,&$form_state) {
module_load_include('inc', 'location');
if ($form_state['values']['country'] == '_none') {
unset($form['get-quotes-shipping0']['states']['#options']);
$form['get-quotes-shipping0']['states']['#default_value'] = '_none';
return $form['get-quotes-shipping0']['states'];
}
else {
$states = location_get_provinces($form_state['values']['country']);
$form['get-quotes-shipping0']['states']['#options'] = $states;
return $form['get-quotes-shipping0']['states'];
}
}
When I select Country and then state at first it gives proper values but when I select country again it gives An illegal choice has been detected
What is the issue with the above code? can anyone point out?
$form['get-quotes-shipping0']['states']['#options']
, that form element doesn't have anymore options; therefore, even the option you select after is correct, because it is not listed in$form['get-quotes-shipping0']['states']['#options']
.