Dynamic select forms I have created a custom form in Drupal 8 where I want to select a vehicle make, populate the models under the vehicle make and avail the list for selection in another field. I am stuck at the Ajax callback I have googled but haven't found a solution. I need guidance on how to use Ajax to get the desired results. My code is the following.

$query = \Drupal::database()-&gt;select('vehicle_make', 'veh');
$query-&gt;fields('veh', ['make_id','make_name']);
$results = $query-&gt;execute();
$options_makes = array();

foreach ($results as $result) {
$options_makes[$result-&gt;make_id] = $result-&gt;make_name;
}

$form['vehicle_make'] = array(
  '#type' =&gt; 'select',
  '#title' =&gt; $this-&gt;t('Vehicle Make'),
  '#options' =&gt; $options_makes,
  '#default' =&gt; '--Select Make --',
  '#ajax' =&gt; array(
    'callback' =&gt; 'ajaxfunction',
    'wrapper' =&gt; 'vehicle-model',
    'effect' =&gt; 'slide',
    ),
);  

$form['vehicle_model_container'] = array(
  '#type' =&gt; 'container',
  '#prefix' =&gt; '&lt;div id="vehicle-model"&gt;',
  '#suffix' =&gt; '&lt;/div&gt;',
);

if ($form_state-&gt;hasValue('vehicle_make')) {
  $vehicle_make = $form_state-&gt;getValue('vehicle_make');
  $subquery = \Drupal::database()-&gt;select('vehicle_model', 'md');
  $subquery-&gt;join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery-&gt;fields('md', ['model_id','model_name']);
  $subquery-&gt;condition('md.make_id', $vehicle_make);
  $results = $subquery-&gt;execute(); 
  $model_options = array();

  foreach ($results as $result) {
    $model_options[$result-&gt;model_id] = $result-&gt;model_name;
  }

  $form['vehicle_model_container']['model'] = array(
    '#type' =&gt; 'select',
    '#title' =&gt; t('Vehicle Model'),
    '#options' =&gt; $model_options,
  );

  function ajaxfunction(array $form, FormStateInterface $form_state) {
    return $form['vehicle_model_container'];
  }
You shouldn't return fetched array as result, in Drupal ajax the return value from the ajax function actually overwrites the wrapper, so you've got to set $form['vehicle_model']['#options'] with fetched value and the return this piece of form ($form['vehicle_model']) as function return value. so the code will be something like this :

function _ajaxfunction(array $form, FormStateInterface $form_state) {
  $vehicle_make = $form_state-&gt;getValue('vehicle_make');
  $subquery = \Drupal::database()-&gt;select('vehicle_model', 'md');
  $subquery-&gt;join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery-&gt;fields('md', ['model_id','model_name']);
  $subquery-&gt;condition('md.make_id', $vehicle_make);
  $results = $subquery-&gt;execute(); $options_models = array();
  foreach ($results as $result) {
    $options_models[$result-&gt;model_id] = $result-&gt;model_name;
  }
  $form['vehicle_model']['#options'] = $options_models;
  return $form['vehicle_model'];
}