I have two select elements. one for a property and one for a category. When I select property it goes to a function through ajax and return an array to other select elements (category) #option
. I need to do is,
when I select a property, the category elements first option should be selected and trigger that elements on change event.
Form
public function buildForm(
array $form,
FormStateInterface $form_state,
$properties = [],
$categories = [],
$propertyContent = [],
$isCorporate = false,
$propertyId = null
) {
$propertyKey = null;
if (!empty($form_state->getValue('property'))) {
$propertyKey = $form_state->getValue('property');
} else {
$propertyKey = key($properties);
}
$form['property'] = [
'#type' => 'select',
'#id' => 'property',
'#attributes' => ['class' => ['form-control']],
'#title' => $this->t('Hotel'),
'#options' => $properties,
'#default_value' => $propertyKey,
'#ajax' => [
'callback' => 'create_category_list',
'event' => 'change',
'wrapper' => 'category-type',
'method' => 'html'
],
'#required' => true,
'#validated' => true,
];
$form['category'] = [
'#type' => 'select',
'#id' => 'category',
'#attributes' => ['class' => ['form-control']],
'#title' => $this->t('Category'),
'#options' => $categoryList,
'#ajax' => [
'callback' => 'show_gallery_ajax',
'event' => 'change',
'wrapper' => 'gallery-images',
'method' => 'html',
'progress' => [
'type' => 'throbber',
'message' => t('Loading gallery !'),
],
],
'#prefix' => '<div id ="category-type">',
'#suffix' => '</div>',
'#default_value' => $defaultCategory,
'#required' => false,
'#validated' => true,
];
return $form;
}