Score:3

Can we add custom CSS class in \Drupal::messenger()->addStatus()?

cn flag

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>
Score:5
fr flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.