I am using headless Drupal with .NET middleware. I have a Drupal 9 form. This form contains two drop-down elements which are filled up depending on a value selected in a third drop-down. I have a custom validation handler just after those AJAX drop-down elements, where I store some data in a .NET database.
This is my code for hook_form_alter()
.
$form['technology_type'] = [
'#type' => 'select',
'#title' => t('Technology Type'),
'#options' => $tech_type_options,
'#default_value' => $t_selected_option,
'#ajax' => [
'callback' => 'techlistDropdownCallback',
'wrapper' => 'techlist-fieldset-container',
'event' => 'change',
],
];
if ($t_selected_option != '') {
$tech_options = array(0 => '- None -');
$tech_options = custom_authorization_tech_options($t_selected_option);
}
else {
$tech_options = array(0 => '- None -');
}
$form['techlist-select-fieldset-container']= [
'#type' => 'container',
'#attributes' => ['id' => 'techlist-fieldset-container'],
];
$form['techlist-select-fieldset-container']['source_tech'] = [
'#type' => 'select',
'#title' => t('Source Tech'),
'#options' => $tech_options,
'#default_value' => !empty($source_tech_value) ? $source_tech_value : $form_state->getValue('source_tech'),
'#multiple' => true,
];
$form['techlist-select-fieldset-container']['target_tech'] = [
'#type' => 'select',
'#title' => t('Target Tech'),
'#options' => $tech_options,
'#default_value' => !empty($target_tech_value) ? $target_tech_value : $form_state->getValue('target_tech'),
'#multiple' => true,
];
if ($t_selected_option == 0) {
$form['techlist-select-fieldset-container']['source_tech']['#title'] = t('Source Tech (You must choose tech type first)');
$form['techlist-select-fieldset-container']['source_tech']['#disabled'] = TRUE;
$form['techlist-select-fieldset-container']['target_tech']['#title'] = t('Target Tech (You must choose tech type first)');
$form['techlist-select-fieldset-container']['target_tech']['#disabled'] = TRUE;
}
array_unshift($form['#validate'],'custom_authorization_mak_form_validate');
Whenever these dependent drop-downs get filled up with values, the validation function gets called somehow and incomplete data gets automatically stored in database even without pressing the save button of the form.
How do I avoid this weird issue?
I just want to fill up the drop-down elements using AJAX, then call the validation handler to store data in database.