I am trying to load a Drupal form through an AJAX callback when the user selects an option from a select list. The code used to generate this form as follows:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['dashboard_list'] = array(
'#title' => t('Select Dashboard:'),
'#type' => 'select',
'#ajax' => array(
'callback' => 'Drupal\dashboard\Controller\DashboardController::OnPanelSwitch',
'effect' => 'fade',
'event' => 'change',
'progress' => array(
'type' => 'throbber',
'message' => NULL,
),
),
);
return $form;
}
Inside of OnPanelSwitch(), which is called when the user selects an option from the list. I am using the renderer service to get the form's HTML and then inserting the form into a div.
public static function OnPanelSwitch(array &$form, FormStateInterface $form_state) {
$ajax_response = new AjaxResponse();
$AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');
$AddChartFormHTML =\Drupal::service('renderer')->render($AddChartForm);
$ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartFormHTML));
return $ajax_response;
}
This HTML is then inserted into a DIV in the page. The form being loaded via AJAX is built in the following manner and contains a single select list:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['query_type'] = array(
'#title' => t('Query Type'),
'#title_display' => 'invisible',
'#type' => 'select',
'#options' => array(t('Chart'), t('Table')),
'#prefix' => '<div class="floatLeft"',
'#suffix' => '</div>',
'#ajax' => array(
'callback' => 'Drupal\dashboard\Controller\DashboardController::OnQueryFieldChange',
'effect' => 'fade',
'event' => 'change',
'progress' => array(
'type' => NULL,
'message' => NULL,
),
),
);
return $form
}
The OnQueryFieldChange() callback is not being called when this form is being loaded via the initial AJAX call. If I load this form without AJAX through the twig template everything works correctly. So it seems to be an issue of the form being loaded via AJAX.
From my research it seems like I might have todo something with Drupal Behaviors to enable AJAX for this form? Any guidance would be really helpful.
Drupal.attachBehaviors();
when the request completes