Skip to content

Instantly share code, notes, and snippets.

@mparker17
Created August 17, 2018 20:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mparker17/a96382554fb41411d85201933a8b0f82 to your computer and use it in GitHub Desktop.
Save mparker17/a96382554fb41411d85201933a8b0f82 to your computer and use it in GitHub Desktop.
Drupal 8 Form API #ajax.callback

'#ajax' => ['callback' is weird.

Looking at examples from Drupal core, there seems to be a bunch of different ways you can call it...

  • 'callback' => 'some_global_function' is the simplest and always seems to work, but the function it calls has to be defined in a .module file, not a class.

  • 'callback' => [$this, 'someFunction'] works sometimes, but you get a 'cannot serialize database service' error if any of $this' properties (or anything they reference) involves a database connection.

  • 'callback' => [static::class, 'someFunction'] works, but calls someFunction() in a static context, meaning you can't use $this->someService->doSomething().

    This is equivalent to, and has the same problems as:

    • 'callback' => [get_class($this), 'someFunction'],
    • 'callback' => '\Fully\Qualified\Class::someFunction',
    • 'callback' => get_called_class() . '::someFunction', and
    • 'callback' => __CLASS__ . '::someFunction'.
  • 'callback' => '::someFunction' is supposed to work in a dynamic context, but it only works on objects that implement FormInterface — so if your hook_form_alter() calls another class to do some of its work and that class wants to define an AJAX callback, it cannot (at least, not out-of-the-box)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment