Declarative Form AJAX

Created on 23 May 2024, 4 months ago
Updated 17 July 2024, about 2 months ago

Problem/Motivation

Currently, making a form element update via AJAX requires setting up the #ajax property on the element, and implementing a form AJAX callback. Typically this callback just returns the form element like this:

function myCallback($form, FormStateInterface $form_state) {
  return $form['my_element'];
}

That's pointless boilerplate code.

Furthermore, you can only update a single form element with this system. You can't have multiple parts of the form update in response to one element.

Nor can you extend a form by having elements added with hook_form_alter() react to an element that's already an AJAX trigger.

Proposed resolution

Introduce a declarative AJAX system, similar to how form states work, like this:

$form['controlling_element'] = [
  '#type' => 'checkbox',
  '#title' => 'Click me',
];

// This container is automatically updated when the user changes the value of
// the controlling_element checkbox.
$form['my_container'] = [
  '#type' => 'container',
  '#ajax' => [
    'updated_by' => [
      // Form parents of the controlling element.
      ['controlling_element'],
    ],
  ],
];

Multiple elements can declare that they are updated by one controlling element, and conversely, one element can be updated by more than one controlling element. There is no longer the need for a callback: everything is declared in the form elements.

I've created a proof-of-concept module with working demos here: https://www.drupal.org/project/declarative_form_ajax β†’

This requires a few tweaks, but those wouldn't be necessary within core.

Remaining tasks

Create a core MR.

User interface changes

None.

API changes

See above.

Data model changes

None.

Release notes snippet

✨ Feature request
Status

Active

Version

11.0 πŸ”₯

Component
FormΒ  β†’

Last updated less than a minute ago

Created by

πŸ‡¬πŸ‡§United Kingdom joachim

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024