I am using Drupal 9. I know how to change single dropdown list using another one. Here is my scenario:
I have three dropdowns, in node form - company, protocol and investigator. What I like to do, when some one select a value in company dropdown, other two dropdown list which change based on selection.
I have written some code, I see the list is updating but its not refreshing.
function hook_form_alter() {
....
case 'node_tsr_form':
case 'node_tsr_edit_form':
$form['field_tsr_pi']['#prefix'] = '<div id="my-module-principal-investigator-wrapper">';
$form['field_tsr_pi']['#suffix'] = '</div>';
$form['field_protocol']['#prefix'] = '<div id="my-module-tsr-protocol-wrapper">';
$form['field_protocol']['#suffix'] = '</div>';
$form['field_company']['widget']['#ajax'] = [
'callback' => 'my_module_ajax_callback_tsr_pi_and_protocol',
'event' => 'change',
'progress' => [
'type' => 'throbber',
'message' => t('loading ...'),
],
];
$company_val = $form_state->getValue('field_company');
if (isset($company_val[0]['target_id'])) {
$company_id = $company_val[0]['target_id'];
}
if (!empty($company_id)) {
$form['field_protocol']['widget']['#options'] = my_module_get_protocols($company_id);
$form['field_pi']['widget']['#options'] = my_module_get_investigator($company_id);
}
else {
$form['field_protocol']['widget']['#options'] = ['_none' => '- None -'];
$form['field_pi']['widget']['#options'] = ['_none' => '- None -'];
}
...
/**
* Called via Ajax callback.
*/
function my_module_ajax_callback_tsr_pi_and_protocol(array &$form, FormStateInterface $form_state) {
$company_val = $form_state->getValue('field_company');
if (isset($company_val[0]['target_id'])) {
$company_id = $company_val[0]['target_id'];
}
if (!empty($company_id)) {
$form['field_protocol']['widget']['#options'] = my_module_get_approved_aup_options($company_id);
$form['field_tsr_pi']['widget']['#options'] = my_module_get_acitve_user_options($company_id);
}
else {
$form['field_protocol']['widget']['#options'] = ['_none' => '- None -'];
$form['field_tsr_pi']['widget']['#options'] = ['_none' => '- None -'];
}
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-module-tsr-protocol-wrapper',$form['field_protocol']));
$response->addCommand(new ReplaceCommand('#my-module-principal-investigator-wrapper', $form['field_tsr_pi']));
return $response;
}
If anyone can help me out, will be really great!!!