2

I want to display an error message when I submit a form. I added an AJAX callback to the form, and the error message appears after I refreshed the page.

I first tried the following code, but it doesn't work.

$response = new \Drupal\Core\Ajax\AjaxResponse();
$message = drupal_get_messages();
$output = $response->addCommand(new \Drupal\Core\Ajax\PrependCommand(".region-highlighted",$message));
return $output;

I also tried the following code.

$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;
2
  • 1
    have you found a solution, i got the same problem ... checked all settings and permissions .. but anonymous users won't get the message ..
    – rémy
    May 18, 2016 at 14:12
  • did you solve your problem? where did you put your second try?
    – Asy
    Mar 7, 2017 at 16:03

2 Answers 2

1

You should retrieve the errors with $form_state->getErrors().

So, you should have something like:

/**
   * Ajax submit handler.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    drupal_get_messages();
    $response = new AjaxResponse();
    if ($form_state->getErrors()) {
      unset($form['#prefix']);
      unset($form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response->addCommand(new ReplaceCommand('#my-id', $form));
    }

    return $response;
  }

Check Examples for Developers for more details.

0

this works for form messages (in a regular ajax form callback):

    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $response->addCommand(new ReplaceCommand('#yourFormWrapperElement', $form));

but using drupal_get_messages() screw's things somehow up .... sometimes. plus you need enable showing messages here: /admin/config/development/logging

So - your second try should also work !

$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;

Maybe the mentioned settings are needed ..

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.