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;
}
}