I am using the following code for a form.
public function buildForm(array $form, FormStateInterface $form_state) {
$region_options = static::getFirstDropdownOptions();
$form['vvv_region'] = [
'#type' => 'select',
'#title' => $this->t('region select field'),
'#options' => $region_options,
'#empty_option' => t('- Select region -'),
'#ajax' => [
'callback' => '::myAjaxCallback',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
$region_selected = $form_state->getValue('vvv_region');
$city_options = static::getSecondDropdownOptions($region_selected);
$form['output'] = [
'#type' => 'select',
'#title' => $this->t('city select field'),
'#options' => $city_options,
'#prefix' => '<div id="edit-output">',
'#suffix' => '</div>',
'#empty_option' => t('- Select city -'),
'#default_value' => '',
'#ajax' => [
'callback' => '::cityAjaxCallback',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-city',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
$city_select = $form_state->getValue('output');
$suburb_options = static::getSuburbDropdownOptions($city_select);
$form['sur'] = [
'#type' => 'select',
'#options' => $suburb_options,
'#prefix' => '<div id="edit-city">',
'#suffix' => '</div>',
'#empty_option' => t('- Select sururb -'),
'#default_value' => array(''),
];
return $form;
}
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
$region_selected = $form_state->getValue('vvv_region');
$city_options = static::getSecondDropdownOptions($region_selected);
if ($form_state->getErrors()) {
\Drupal::messenger()->addError($region_selected);
$form_state->setRebuild();
}
$form['outpout']['#options'] = $city_options;
return $form['output'];
}
public function cityAjaxCallback(array &$form, FormStateInterface $form_state) {
$city_select = $form_state->getValue('output');
$sur_data = static::getSuburbDropdownOptions($city_select);
if ($form_state->getErrors()) {
\Drupal::messenger()->addError($city_select);
$form_state->setRebuild();
}
$form['sur']['#options'] = $sur_data;
return $form['sur'];
}
When the form is submitted, I get the following error.
An invalid selection has been identified. Please contact the site administrator.
What's wrong with the code I am using?