I have a lot of API calls in a form, so in order to not call everything on load, I only want to load it when the user opens the details element.
But I am having trouble adding #ajax to the element. I can see a spinner and that it calls buildForm(), but it is not triggering the callback method. When I wrap the ajax part inside e.g. an checkbox, it works. Thus, I come to the conclusion that it is something with the details element.
How can I create an ajax callback, when the user opens the details element?
Non-working example with ajax on details:
public function buildForm(array $form, FormStateInterface $form_state) {
[...]
return [
'#type' => 'details',
'#title' => $title,
'#open' => FALSE,
'#ajax' => [
'callback' => [$this, 'openAccordion'],
'event' => 'click',
],
];
}
public function openAccordion(array $form, FormStateInterface $form_state) {
$response = new AjaxResponse();
return $response;
}
Working example where ajax is on a button (just an example):
return [
'#type' => 'details',
'#title' => $title,
'#open' => FALSE,
'widget' => [
'#type' => 'button',
'#value' => 'Load',
'#ajax' => [
'callback' => [$this, 'openAccordion'],
'event' => 'click',
],
],
];