1

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.

1 Answer 1

3

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

$form['#attached']['library'][] = 'views/views.ajax';
1
  • 1
    That was it. Thanks. Odd this one command needs an extra library attached and nothing in the documentation: drupal.org/docs/drupal-apis/ajax-api/… 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.
    – liquidcms
    Dec 9, 2022 at 1:34

Your Answer

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

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