The class documentation of InsertCommand and all commands extending it only state that they accept HTML as input content, while InsertCommand::construct() correctly states that it accepts a render array or an HTML string. But passing HTML creates problems with AJAX forms.
The problem is that the documentation erroneously push developers to convert render arrays into HTML, with \Drupal::service('renderer')->render(), before passing the output to the AJAX command. It often happens with Form API elements. Any element which had '#ajax' properties set will lose them if they are rendered as HTML before being passed to one of these AJAX commands.
If instead of passing HTML, the render array was passed directly to one of these AJAX commands, the '#ajax' properties will work as expected.
This kind of issue can be hard to debug since the documentation seems to indicate we have to use HTML with these AJAX commands.
Affected:
- AfterCommand
- AppendCommand
- BeforeCommand
- HtmlCommand
- InsertCommand
- PreprendCommand
- ReplaceCommand
- Maybe OpenDialogCommand which also uses CommandWithAttachedAssetsTrait
Proposed fix: update the class documentation of these commands to indicate they accept render arrays. It could also help to mention best practices about handling render arrays with AJAX commands on https://api.drupal.org/api/drupal/core!core.api.php/group/ajax/
Original issue content:
I am trying to create an Ajax form with three dependent selects, following the Ajax guide provided by Examples module https://api.drupal.org/api/examples/fapi_example!src!Form!AjaxDemo.php/c...
The first two select works perfectly, but the render of third doesn't work, the select in return by a callback function.
Let me show you the fist select code
$form['state'] = array(
'#type' => 'select',
'#title' => $this->t('State'),
'#description' => $this->t('Please select your favorite state'),
'#options' => $this->states,
'#size' => 1,
'#empty_option' => $this->t('-select-'),
'#ajax' => array(
'callback' => '::updateCities',
'wrapper' => 'city-wrapper',
'event' => 'change',
'progress' => array(
'type' => 'throbber',
'message' => "searching",
),
)
);
$form['city_wrapper'] = [
'#type' => 'container',
'#attributes' => ['id' => 'city-wrapper'],
];
Below the callback function
function updateCities($form, FormStateInterface $form_state) {
$state = $form_state->getValue('state');
if(!empty($this->cities[$state])) {
$form['city_wrapper']['city'] = array(
'#attributes' => ['id' => 'city-wrapper'],
'#type' => 'select',
'#title' => $this->t('City'),
'#description' => $this->t('Please select your favorite city'),
'#size' => 1,
'#empty_option' => $this->t('-select-'),
'#options' => $this->cities[$state],
'#ajax' => array(
'callback' => '::updateStudies',
'wrapper' => 'study-wrapper',
'event' => 'change',
'progress' => array(
'type' => 'throbber',
'message' => "searching",
),
)
);
}
$response = new AjaxResponse();
$response->addCommand(new InsertCommand('#taxonomy-term-data-form', $form['city_wrapper']['city']));
return $response;
}
The second select is render properly but without ajax effect to render the third select, I tried returning the FAPI element with the same result.
Here an image of first two select elements working.

In addition, the second select don't allow to be render without selection the first element is immediately selected, I don't know if this a separate issue.
| Comment | File | Size | Author |
|---|---|---|---|
| #18 | 2758915-18.patch | 4.87 KB | darvanen |
Issue fork drupal-2758915
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #9
amber himes matz0. FYI, the link to the AJAX Dependent Dropdown example in the original report is broken. Looks like this example has been moved to:
D9 - https://git.drupalcode.org/project/examples/-/blob/3.x/modules/ajax_exam...
D8 - https://git.drupalcode.org/project/examples/-/blob/8.x-1.x/ajax_example/...
1. Also, I did notice that it looks like you have a typo in your
function updateCitiesin the following section:The
'callback' => '::updateStudies',-- is that right? Should it be'callback' => '::updateCities',? This could be why it's not working for you.3.
If it's a "dependent dropdown", wouldn't that be by design?
Please update the issue if this is still a problem, or close if it's no longer an issue. I'm inclined to close as "cannot reproduce".
Comment #10
amber himes matzClosing, but feel free to re-open if you feel like it's still an issue/bug in core.
Comment #11
mdupontI kind of reproduced this issue on Drupal 8.9, and I think it is a more of a documentation issue.
TL;DR: Reuse a similar code as above, except that this time, in the AJAX callback you call
\Drupal::service('renderer')->render()on the updated form field before passing the result to theInsertCommand()or theReplaceCommand(). The #ajax behavior on the updated field will be lost.Now, keep in mind that Drupal's documentation advises to use
\Drupal::service('renderer')->render()when updating form elements! See https://www.drupal.org/docs/drupal-apis/javascript-api/ajax-forms#ajax_c...Possible next steps:
Update the AJAX API documentation to mention this pitfall.
Update Drupal Wiki's AJAX Forms documentation to remove the usage of the Renderer service in the code samples, since it seems to be both unnecessary and harmful.
Long version
Situation: a form with a
field_aand afield_bwhich have #ajax properties to update themselves, and afield_cwith #ajax properties to updatefield_aandfield_bbased onfield_cvalue.field_c's AJAX callback sends anAjaxResponsewith twoReplaceCommand().Problem: once updated,
field_aandfield_b#ajax no longer works.Cause: if the form field is rendered with
\Drupal::service('renderer')->render()before being passed to theReplaceCommand(), #ajax behavior willl be lost.If InsertCommand() or ReplaceCommand() are passed an HTML string, #ajax behavior will be lost. If passed a Form API array, behaviors will work as expected, since in this case the attached assets (JS libraries, settings...) will be correctly processed as part of the Response.
Comment #12
mdupontComment #13
mdupontComment #17
darvanenThis came up again as a #bugsmash triage target. Now that it has changed tack to a documentation issue I can attest to having personally run into this very issue. I plan to write a patch if it hasn't been done by the time I have some time to spend on it.
Comment #18
darvanenComment #19
smustgrave commentedThis issue is being reviewed by the kind folks in Slack, #needs-review-queue-initiative. We are working to keep the size of Needs Review queue [2700+ issues] to around 400 (1 month or less), following Review a patch or merge request as a guide.
The changes in #18 make sense to me. Will move this along.
Comment #23
larowlanThis came up the other day in #2977785: No error messages are shown for applied validation on a view exposed filter with on "AJAX" so very timely.
Committed to 10.1.x and backported to 10.0.x and 9.5.x to keep things consistent.