Firstly, a working select element with an AJAX callback:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['select'] = [
'#type' => 'select',
'#options' => [
0 => 'ZERO',
1 => 'ONE',
2 => 'TWO',
],
'#ajax' => [
'callback' => [$this, 'ajaxSelectChanged'],
'event' => 'change',
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
return $form;
}
public function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
$selection = $form_state->getValue('select');
// Do something with the selection.
}
Now I want to put the select element inside a tableselect element...
This comment shows how form elements may be added inside the rows of a tableselect (which is also a form element).
Here's my attempt:
public function buildForm(array $form, FormStateInterface $form_state) {
// Build the sortable table header.
$select_options = [
0 => 'ZERO',
1 => 'ONE',
2 => 'TWO',
];
$form['table'] = [
'#type' => 'tableselect',
'#header' => [
'name' => $this->t('Name'),
'select' => $this->t('Select'),
],
'#options' => [
'alice' => [
'name' => $this->t('Alice'),
'select' => [
'data' => [
'#type' => 'select',
'#options' => $select_options,
'#ajax' => [
'callback' => [$this, 'ajaxSelectChanged'],
'event' => 'change',
],
],
],
],
'bob' => [
'name' => $this->t('Bob'),
'select' => [
'data' => [
'#type' => 'select',
'#options' => $select_options,
'#ajax' => [
'callback' => [$this, 'ajaxSelectChanged'],
'event' => 'change',
],
],
],
],
],
'#empty' => $this->t('There is nothing to see here.'),
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
return $form;
}
public function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
$selection = $form_state->getValues();
// Do something with the selection.
}
It works, except for the AJAX callback, which never runs.
- Am I doing something wrong?
- Is there a way to let form elements inside a table trigger AJAX callbacks when they are changed?