Do you want to know how to Drupal?

Let's Drupal

How to show a message in Drupal 9?

Sometimes we need to inform a user about a result of some operations. For example we have submitted the form and we want to show a success message or an error

We need to user service "messenger" service, which will store the message in the session and fetch during the next request.

Get instance of messenger service

# 1. Standard way to get messenger service, in case you want to pass it using dependency injection.
$messenger = \Drupal::service("messenger");

# 2. Fast way to use helper function.

$messenger = \Drupal::messenger();

Also in the form object or controller we don't have include it using dependency injection. We can us directly 

$messenger = $this->messenger();

Methods

1. Add message. Allows to send a message of any type, the second parameter accepts the type

$meesenger->addMessage(t('Your message.'), MessengerInterface::TYPE_WARNING);

But in most of the cases it is better to use directly specific method

 

2. Add status

$messenger->addStatus(t('Your message'));

 

3. Add warning

$messenger->addWarning(t('Your message'));

 

4. Add error

$messenger->addError(t('Your message'));