1

I have created an AJAX form. After the form is submitted, I call $this->createOkResponse() which updates a section of the page with a message (it replaces the form with the message).

It all works fine except for one thing: the form is quite long and the submit button is at the bottom. When I replace the page content with my ReplaceCommand() the message I am showing comes at the top of the page, but the page doesn't scroll up to the top.

Then I thought I could use a ScrollTopCommand() to force the page to scroll up but it doesn't work. I have checked that the body does have the scroll bars. I have tried with body with html and with html, body as the selector but nothing works.

I have cleared the caches multiple times and I get no error in the error logs or the Javascript console. Just the page doesn't scroll up and my OK message remains hidden until I manually scroll up.

I see that ScrollTopCommand is part of Views. Does that prevent me from using it in a form?

Edit: I have also tried setting views as a dependency in my module info YAML file but that didn't change anything.

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\views\Ajax\ScrollTopCommand;

/**
 * Class InterventionForm.
 */
class InterventionForm extends FormBase
{

  /**
   * Function to update the page with AJAX with an OK
   * @retun $response AjaxResponse
   */
  protected function createOkResponse(): AjaxResponse
  {

    $response = new AjaxResponse();

    $render_array = [
      '#markup' => '<div class="bg-success">OK Response!</div>'
    ];

    // Replace content with our response
    $response->addCommand(new ReplaceCommand('#interventionCreate', $render_array));

    // Scroll to top of page
    $response->addCommand(new ScrollTopCommand('body'));

    return $response;
  }
}

1 Answer 1

2

The module dependency doesn't help because Views is already installed by default, but keep it in case someone tries to uninstall the module. The next step is then to include the modules ajax library in buildForm():

$form['#attached']['library'][] = 'views/views.ajax';
3
  • Ah! Thanks a lot! Works like a charm :)
    – MrUpsidown
    Aug 19, 2022 at 13:31
  • Should it not trigger a JS error when the library is not included?
    – MrUpsidown
    Aug 25, 2022 at 13:49
  • 1
    No, ajax.js only runs commands which exist in the command list client-side. Check the new 9.5.x version, much cleaner and easier to read than previous releases: git.drupalcode.org/project/drupal/-/blob/9.5.x/core/misc/…
    – 4uk4
    Aug 25, 2022 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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