Adding #ajax callbacks to form elements in HOOK_form_alter()

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!

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Adding #ajax callbacks to form elements in HOOK_form_alter()

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.