I’m trying to add an #ajax callback to a select element on a form that is created in another module on a Drupal 8.x site. When I add the #ajax callback using HOOK_form_alter() in my module, the Ajax callback starts running and the Ajax throbber appears after changing the selection in the ajaxified select element, but then an exception is thrown and my callback function is never called:
Uncaught PHP Exception SymfonyComponentHttpKernelExceptionHttpException: "The specified #ajax callback is empty or not callable." at /var/www/drupal/public_html/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php line 70
It seems the [‘#ajax’][‘callback’] is not available in FormAjaxResponseBuilder.php when the callback was added using HOOK_form_alter. If I use the exact same code (except the $this pointer) in my own custom form in buildForm(..) it works as expected.
Is this by design or is there another way to attach an ajax callback to an existing form’s elements?
The form that I’m trying to alter in my module’s HOOK_form_alter is created with a code like that in the other module’s /modulename/src/Form/DefaultForm.php:
/**
* Class DefaultForm.
*/
class DefaultForm extends FormBase {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state)
{
$form['example_select'] = [
'#type' => 'select',
'#title' => $this
->t('Select element'),
'#options' => [
'1' => $this
->t('One'),
'2' => [
'2.1' => $this
->t('Two point one'),
'2.2' => $this
->t('Two point two'),
],
'3' => $this
->t('Three'),
],
//removed the callback from this form declaration. it works when ajax
//event is added here.
//trying to add ajax callback in form_alter in .module file instead.
//'#ajax' => [
// 'callback' => [$this, 'ajaxCallback'],
// 'wrapper' => 'ajax-callback-target',
//]
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
}
Now back in my other module’ ajaxfilters.module file I’m trying to add the ajax callback to the form above using HOOK_form_alter.
function ajaxfilters_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
if($form['#id'] == 'default-form')
{
//add ajax event to the select element
$form['example_select']['#ajax'] = [
'callback' => 'myCallback',
'event' => 'change',
'wrapper' => 'ajax-callback-target',
];
//add container that receives the result of our callback
$form['callback_target'] = [
'#type' => 'container',
'#attributes' => [
'id' => ['ajax-callback-target'],
],
];
} // EOF default-form
}
function myCallback(&$form, FormStateInterface $form_state)
{
error_log("inside myCallback");
$markup = '<h1>H3llo!</h1>';
return ['#markup' => $markup];
}
When I now change the selection in the ajaxified select element, a throbber appears, but I end up with the exception described above.
I first thought it’s a matter of scope and that my callback can’t be accessed from FormAjaxResponseBuilder.php so I checked the code that throws the exception:
public function buildResponse(Request $request, array $form, FormStateInterface $form_state, array $commands) {
// If the form build ID has changed, issue an Ajax command to update it.
if (isset($form['#build_id_old']) && $form['#build_id_old'] !== $form['#build_id']) {
$commands[] = new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']);
}
// We need to return the part of the form (or some other content) that needs
// to be re-rendered so the browser can update the page with changed
// content. It is up to the #ajax['callback'] function of the element (may
// or may not be a button) that triggered the Ajax request to determine what
// needs to be rendered.
$callback = NULL;
if (($triggering_element = $form_state->getTriggeringElement()) && isset($triggering_element['#ajax']['callback'])) {
$callback = $triggering_element['#ajax']['callback'];
}
$callback = $form_state->prepareCallback($callback);
if (empty($callback) || !is_callable($callback)) {
throw new HttpException(500, 'The specified #ajax callback is empty or not callable.');
}
$result = call_user_func_array($callback, [&$form, &$form_state, $request]);
The problem seems to be within here. $form_state->getTriggeringElement() correctly returns the select element, where I added my ajax callback, but the [‘#ajax’][‘callback’] is missing here, ie. isset($triggering_element[‘#ajax’][‘callback’]) returns false.
To rule out that’s it’s a problem with the scope I just added $callback = ‘myCallback’ right above the check if(empty($callback)). If I do so, my callback can successfully be executed.
How would I add an ajax callback to an existing form’s elements if not by using HOOK_form_alter?
Thank you very much for your help!