I'm trying to add AJAX callback to form element that was previously rendered by AJAX but with no luck. Code below.
A bit of description. There are three main methods here:
buildForm
- base formextraField
- AJAX callback attached to['month']
choosePerson
- AJAX callback attached to:['week_day']['hour']
In the buildForm method I create base form with AJAX callback on 'month' select element. In the AJAX callback you can find an extraField method. This method contains form element called 'hour' ($form['week_day']['hour']
) and this element renders well. But this element also contains AJAX callback, which doesn't work, it does not generate 'person_container' element and the 'person' select.
Any idea how to ajaxify elements that previously were rendered by ajax?
class ReservationForm extends FormBase {
public function getFormId() {
return 'reservation_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['month'] = array(
'#type' => 'select',
'#title' => $this->t('Select month'),
'#options' => array($this->t('January'), $this->t('February'), $this->t('March')),
'#ajax' => array(
'callback' => array($this, 'extraField'),
'event' => 'change',
'wrapper' => 'week-day',
),
);
// Disable caching on this form.
$form_state->setCached(FALSE);
$form['week_day'] = [
'#type' => 'container',
'#attributes' => ['id' => 'week-day'],
];
}
public function extraField(array &$form, FormStateInterface $form_state) {
$month = $form_state->getValue('month');
$hour_options = array();
if ($month == '0') {
$hour_options[0] = $this->t('08:00');
$hour_options[1] = $this->t('09:00');
$hour_options[2] = $this->t('10:00');
}
if ($month == '1') {
$hour_options[0] = $this->t('12:00');
$hour_options[1] = $this->t('13:00');
$hour_options[2] = $this->t('14:00');
}
if ($month == '2') {
$hour_options[0] = $this->t('18:00');
$hour_options[1] = $this->t('19:00');
$hour_options[2] = $this->t('20:00');
}
$form['week_day']['hour'] = array(
'#type' => 'select',
'#title' => $this->t('Choose hours @month', array('@month' => $month)),
'#options' => $hour_options,
'#ajax' => array(
// tried with that callback too: [ $this, 'choosePerson']
'callback' => array($this, 'choosePerson'),
'event' => 'change',
'wrapper' => 'person',
),
);
$form['week_day']['person_container'] = array(
'#type' => 'container',
'#attributes' => ['id' => 'person-container'],
);
$form['week_day']['person_container']['person'] = array(
'#type' => 'select',
'#title' => $this->t('Choose person'),
'#options' => ['John', 'Sarah', 'Peter'],
);
return $form['week_day'];
}
public function choosePerson(array &$form, FormStateInterface $form_state) {
$form['week_day']['person_container']['person'] = array(
'#type' => 'select',
'#title' => $this->t('Choose person'),
'#options' => ['John', 'Sarah', 'Peter'],
);
return $form['week_day']['person_container'];
}
}