Score:1

Why is ScrollTopCommand not working?

us flag

I have a node edit form which I submit via ajax and then opens a modal doing this:

  $form['actions']['submit'] = array_merge($form['actions']['submit'], [
    '#value' => t('Get quote'),
    '#ajax' => [
      'callback' => 'open_quote_modal',
      'event' => 'click',
    ]
  ]);
  $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

This works fine. In my ajax call from this submit I do the following to capture any errors from the node edit form:

function open_quote_modal($form, $form_state) {
  $response = new AjaxResponse();

  // Check that there werent any errors from the Quote form.
  if ($form_state->hasAnyErrors()) {
    $allMessages = \Drupal::messenger()->all();
    $allMessages['#type'] = 'status_messages';
    $html = \Drupal::service('renderer')->renderRoot($allMessages);

    // Remove any old messages.
    $response->addCommand(new RemoveCommand('.messages'));
    // Add new messages.
    $response->addCommand(new AfterCommand('div[data-drupal-messages-fallback]', $html));
    // Scroll to top of page.
    $response->addCommand(new ScrollTopCommand('body'));

    return $response;
  }

  // If no errors - code here to show contents of modal
}

This also works perfectly, except for the ScrollTopCommand. My errors are shown at the top of the page but I am left at the bottom of the page. There are no js or php errors.

Score:2
de flag

You need to include the views/views.ajax lib:

$form['#attached']['library'][] = 'views/views.ajax';
liquidcms avatar
us flag
That was it. Thanks. Odd this one command needs an extra library attached and nothing in the documentation: https://www.drupal.org/docs/drupal-apis/ajax-api/core-ajax-callback-commands about this. Of course nothing in the documentation about requiring the drupal.dialog.ajax library either. Likely would make sense for this to be moved into the core library. I have used modals with ScrollTop before and never added this; but guessing they have Views on those pages so it gets added from that.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.