0

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 Symfony\Component\HttpKernel\Exception\HttpException: "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!

  • Does the code that adds the ajax callback get run when the ajax event happens? – Charles Bamford Jul 1 at 16:40
  • Is there multiple forms and/or other select elements with the same name, id, or css class in the page? – Ismail Cherri Jul 1 at 22:43
  • My best guess is that $form['#id'] changes when ajax is called, so the callback isn't added when the form is rebuilt. I'd suggest using $form_state->getObject() instanceof FormClass to make sure you have the correct form instead. – Charles Bamford Jul 1 at 23:40
  • To add on to what Charles said, you can also use the $form_id variable from the arguments in hook_form_alter(). As far as it goes, you can add #ajax in hook_form_alter() with no problem. The callback function must be available. – Jaypan Jul 2 at 3:59
  • @CharlesBamford Thanks so much! You're right, the form_alter is only called when the page is loaded. But when the Ajax callback happens, the form gets rebuilt with another $form['#id']. So the code that adds the Ajax callback function is not run again. Jaypan I changed the check to if( $form_id == 'default_form') and the form_alter "survives" when the form is rebuilt. Actually I only used $form['#id'] because I was trying to add an Ajax callback to a an exposed views filter where $form_id is not available. But this is a whole different story ;) Thank you guys for your answers! – electric.larry Jul 3 at 21:10
0

The problem - as Charles Bamford pointed out in the comments - is in the form_alter where the form id is checked.

if($form['#id'] == 'default-form')

The $form['#id'] changes each time the form is rebuilt when the Ajax callback happens. If you use above comparison, the code that attaches the Ajax callback will only be executed once the page is loaded, but not when the ajax callback happens.

This leads to the error:

Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\HttpException: "The specified #ajax callback is empty or not callable." at /var/www/drupal/public_html/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php line 70

To fix the problem change the comparison in 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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.