I have a taxonomy option list make where I choose say Toyota.
- I want the second taxonomy option list with the models of Toyota only (Eg. Corolla, hilux etc...).
- When I choose Benz the second list will then contains C-Class, ML, etc...
I have created the entity vehicle from google examples on xampp localhost, windows 10.
In my vehicle form I'm able to populate the first list. But the second appears empty.
Here is my code. Please help:
public function buildForm(array $form, FormStateInterface $form_state, $params = NULL) {
$options = array();
$tax = "make";
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree($tax, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
foreach ($terms as $term) {
$options[] = $term->name;
}
$form['make'] = array(
'#type' => 'select',
'#title' => t('Make'),
'weight' => 0,
'#options' => $options,
'#ajax' => array(
'callback' => [$this, 'changeOptionsAjax'],
'wrapper' => 'model_wrapper',
),
);
$form['model'] = array(
'#type' => 'select',
'#title' => t('Model'),
'weight' => 1,
'#options' => $this->getOptions($form_state),
'#prefix' => '<div id="model_wrapper">',
'#suffix' => '</div>',
);
return $form;
}
public function getOptions(FormStateInterface $form_state) {
$options = array();
if ($form_state->getValue('make') == "Benz") {
$tax="benz";
}
elseif ($form_state->getValue('make') == "BMW") {
$tax="bmw";
}
elseif ($form_state->getValue('make') == "Toyota") {
$tax="toyota";
}
else {
$tax="title";
// title is just another taxonomy list I'm using as default if make is not found
}
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree($tax, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
foreach ($terms as $term) {
$options[] = $term->name;
}
return $options;
}
public function changeOptionsAjax(array &$form, FormStateInterface $form_state) {
return $form['model'];
}
Here I give you a working sample based on your example
VehiculesForm.php
:I took the liberty to rename some variable for better readability.
Also, I suggest you to make some improvments on you code such:
switch
but link your taxonomies with a reference fields.$options[$brand->getName()] = $brand->getName();
and use something like$options[$brand->id()] = $brand->getName();
.Hope it will help you !