3

I did some research regarding adding custom CSS classes in the message but could not find the actual solution.

As per Drupal 9 documentation:

\Drupal::messenger()->addMessage(t($message));

public function addMessage($message, $type = self::TYPE_STATUS, $repeat = FALSE);

I don't find the option to add CSS class. On the frontend, I would like to add custom CSS class custom-messages--status in the outputted <div> so that I can format it as desired:

<div class="col-md-12 messages custom-messages--status">Successfully submitted.</div>

1 Answer 1

5

addMessage() accepts a string or a MarkupInterface as its argument. If you intend to pass HTML to addMessage(), you need to construct a render array for that markup then explicitly render it. For example:

$build = [
  '#type' => 'container',
  '#markup' => t('Successfully submitted'),
  '#attributes' => ['class' => ['custom-messages--status']],
];
$message = \Drupal::service('renderer')->renderPlain($build);
\Drupal::messenger()->addMessage($message);

Of course, you should inject these services when possible rather than using static \Drupal:: calls.

0

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.