4

I'm using \Drupal\Core\Form\FormState::setError() in a form validation hook to display a message if the validation fails. I want to include some HTML on it, but the second parameter of setError(), the error message, is escaped. As a result, the HTML code is visible in the message box. How can I avoid this and have HTML in the box?

8

All errors added to the form state will be finally handled by drupal_set_message.
That means that you can either use strings, or any class that implements the MarkupInterface.
Looking at that list I would say that what you are looking for is FormattableMarkup or even better TranslatableMarkup.

An example would then be:

$your_error = new TranslatableMarkup('<b>@message!</b>', array('@message' => 'A bold error'));
$form_state->setError($element, $your_error); 

Good luck!

  • Great answer. t() is the same code, still the most used function in Drupal: api.drupal.org/api/drupal/… – 4k4 Sep 30 '16 at 6:37
  • Works great. I was passing a simple string instead of an instance of TranslatableMarkup. Objects implementing this class, according to the interface documentation, "will not be automatically XSS filtered by the render system or automatically escaped by the theme engine", which is what I needed. In this particular case all code is internal, coming from entityQuery, so security is not affected by avoiding those filters. – kaldimar Sep 30 '16 at 14:22
1

The other answer does not allow HTML inside the @message, here is what worked for me.

  $message = '<b>A bold error</b>';
  $rendered_message = \Drupal\Core\Render\Markup::create($message);
  $error_message = new TranslatableMarkup ('@message', array('@message' => $rendered_message));
  $form_state->setErrorByName('field_name', $error_message);

Important: For security reasons, make sure that $message value is authored by an admin only; otherwise, you cannot use this answer!

Note: You have to declare the new dependency at top of your class.php file, or you will receive an error and WSOD in browser:

use \Drupal\Core\StringTranslation\TranslatableMarkup;

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.