// 1. Create a custom module.
// ...
// 2. Implement Hook Form Alter.
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_CONTENT_TYPE_edit_form') {
// Add your predefined select field.
$form['predefined_select'] = array(
'#type' => 'select',
'#title' => t('Predefined Select Field'),
// Add your options here.
'#ajax' => array(
'callback' => 'mymodule_update_second_select',
'event' => 'change',
'wrapper' => 'second-select-wrapper',
),
);
// Add a wrapper for the second select field.
$form['second_select_wrapper'] = array(
'#prefix' => '<div id="second-select-wrapper">',
'#suffix' => '</div>',
);
}
}
// 3. Implement JavaScript (mymodule.libraries.yml).
custom-scripts:
js:
js/custom.js: {}
// 4. Implement JavaScript (custom.js).
(function ($) {
Drupal.behaviors.mymoduleCustomSelect = {
attach: function (context, settings) {
$('#edit-predefined-select', context).once('mymodule-predefined-select').change(function() {
// Trigger an AJAX call.
Drupal.ajax({url: '/mymodule/ajax/update-second-select'}).execute();
});
}
};
})(jQuery);
// 5. Implement AJAX Callback (mymodule.routing.yml).
mymodule.ajax_update_second_select:
path: '/mymodule/ajax/update-second-select'
defaults:
_controller: '\Drupal\mymodule\Controller\MyModuleController::updateSecondSelect'
_title: 'Update Second Select'
// 6. Implement Controller for AJAX Callback (MyModuleController.php).
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
class MyModuleController extends ControllerBase {
public function updateSecondSelect() {
// Implement your logic to update the options of the second select field.
// Return the updated HTML for the second select field.
return new JsonResponse(array(
'data' => render($second_select_element),
));
}
}