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.

CommentFileSizeAuthor
#18 2758915-18.patch4.87 KBdarvanen
ajaxresponse-no-ajax.png31.27 KB-enzo-

Issue fork drupal-2758915

Command icon 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

-enzo- created an issue. See original summary.

Version: 8.1.x-dev » 8.2.x-dev

Drupal 8.1.9 was released on September 7 and is the final bugfix release for the Drupal 8.1.x series. Drupal 8.1.x will not receive any further development aside from security fixes. Drupal 8.2.0-rc1 is now available and sites should prepare to upgrade to 8.2.0.

Bug reports should be targeted against the 8.2.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.6 was released on February 1, 2017 and is the final full bugfix release for the Drupal 8.2.x series. Drupal 8.2.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.3.0 on April 5, 2017. (Drupal 8.3.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.3.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.6 was released on August 2, 2017 and is the final full bugfix release for the Drupal 8.3.x series. Drupal 8.3.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.4.0 on October 4, 2017. (Drupal 8.4.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.4.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.4 was released on January 3, 2018 and is the final full bugfix release for the Drupal 8.4.x series. Drupal 8.4.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.5.0 on March 7, 2018. (Drupal 8.5.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.5.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.6 was released on August 1, 2018 and is the final bugfix release for the Drupal 8.5.x series. Drupal 8.5.x will not receive any further development aside from security fixes. Sites should prepare to update to 8.6.0 on September 5, 2018. (Drupal 8.6.0-rc1 is available for testing.)

Bug reports should be targeted against the 8.6.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.6.x-dev » 8.8.x-dev

Drupal 8.6.x will not receive any further development aside from security fixes. Bug reports should be targeted against the 8.8.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.9.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.7 was released on June 3, 2020 and is the final full bugfix release for the Drupal 8.8.x series. Drupal 8.8.x will not receive any further development aside from security fixes. Sites should prepare to update to Drupal 8.9.0 or Drupal 9.0.0 for ongoing support.

Bug reports should be targeted against the 8.9.x-dev branch from now on, and new development or disruptive changes should be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

amber himes matz’s picture

0. 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 updateCities in the following section:

'#ajax' => array(
              'callback' => '::updateStudies',
              'wrapper' => 'study-wrapper',
              'event' => 'change',
              'progress' => array(
                  'type' => 'throbber',
                  'message' => "searching",
              ),
          )

The 'callback' => '::updateStudies', -- is that right? Should it be 'callback' => '::updateCities',? This could be why it's not working for you.

3.

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.

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".

amber himes matz’s picture

Status: Active » Closed (cannot reproduce)

Closing, but feel free to re-open if you feel like it's still an issue/bug in core.

mdupont’s picture

Status: Closed (cannot reproduce) » Active

I 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 the InsertCommand() or the ReplaceCommand(). 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_a and a field_b which have #ajax properties to update themselves, and a field_c with #ajax properties to update field_a and field_b based on field_c value. field_c's AJAX callback sends an AjaxResponse with two ReplaceCommand().

Problem: once updated, field_a and field_b #ajax no longer works.

Cause: if the form field is rendered with \Drupal::service('renderer')->render() before being passed to the ReplaceCommand(), #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.

mdupont’s picture

Version: 8.9.x-dev » 9.3.x-dev
Issue summary: View changes
Issue tags: -Needs issue summary update +API Documentation
  • ✓ Examples module doesn't have the code error described in the original issue report anymore
  • ✓ I updated the Drupal Wiki AJAX Forms documentation to remove the code error in the snippet
  • ✕ ReplaceCommand API documentation still needs a fix
mdupont’s picture

Title: FAPI #ajax property in elements is not proccessed by AjaxResponse » AJAX commands documentation is misleading when working with render arrays

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

darvanen’s picture

This 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.

darvanen’s picture

Status: Active » Needs review
StatusFileSize
new4.87 KB
smustgrave’s picture

Status: Needs review » Reviewed & tested by the community
Issue tags: +Needs Review Queue Initiative

This 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.

  • larowlan committed 8a7c0eab on 10.0.x
    Issue #2758915 by mdupont, darvanen, -enzo-, Amber Himes Matz,...

  • larowlan committed bfa2a1bf on 10.1.x
    Issue #2758915 by mdupont, darvanen, -enzo-, Amber Himes Matz,...

  • larowlan committed 7939daf4 on 9.5.x
    Issue #2758915 by mdupont, darvanen, -enzo-, Amber Himes Matz,...
larowlan’s picture

Status: Reviewed & tested by the community » Fixed

This 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.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.