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?
All errors added to the form state will be finally handled by
That means that you can either use strings, or any class that implements the
Looking at that list I would say that what you are looking for is
FormattableMarkup or even better
An example would then be:
$your_error = new TranslatableMarkup('<b>@message!</b>', array('@message' => 'A bold error')); $form_state->setError($element, $your_error);
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: