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;
  • 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 '16 at 14:12
  • did you solve your problem? where did you put your second try? – Asy Mar 7 '17 at 16:03
0

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.

| improve this answer | |
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 ..

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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