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()->select('vehicle_make', 'veh');
$query->fields('veh', ['make_id','make_name']);
$results = $query->execute();
$options_makes = array();
foreach ($results as $result) {
$options_makes[$result->make_id] = $result->make_name;
}
$form['vehicle_make'] = array(
'#type' => 'select',
'#title' => $this->t('Vehicle Make'),
'#options' => $options_makes,
'#default' => '--Select Make --',
'#ajax' => array(
'callback' => 'ajaxfunction',
'wrapper' => 'vehicle-model',
'effect' => 'slide',
),
);
$form['vehicle_model_container'] = array(
'#type' => 'container',
'#prefix' => '<div id="vehicle-model">',
'#suffix' => '</div>',
);
if ($form_state->hasValue('vehicle_make')) {
$vehicle_make = $form_state->getValue('vehicle_make');
$subquery = \Drupal::database()->select('vehicle_model', 'md');
$subquery->join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
$subquery->fields('md', ['model_id','model_name']);
$subquery->condition('md.make_id', $vehicle_make);
$results = $subquery->execute();
$model_options = array();
foreach ($results as $result) {
$model_options[$result->model_id] = $result->model_name;
}
$form['vehicle_model_container']['model'] = array(
'#type' => 'select',
'#title' => t('Vehicle Model'),
'#options' => $model_options,
);
function ajaxfunction(array $form, FormStateInterface $form_state) {
return $form['vehicle_model_container'];
}
'callback' => '::ajaxfunction',
see drupal.stackexchange.com/questions/192060/…