Drupal 8 Messenger Service

For a long time the drupal_set_message() function has been a mainstay of Drupal development. You can use this function to print a message or an error response to a user. This is useful to do as it can be done almost anywhere before the final page rendering functions and will be printed into the same area of a Drupal page.

This has recently been deprecated in Drupal 8.5.0 and so I was looking around on how to do the same thing in a new way. Drupal now has a messenger service, powered by the class Drupal\Core\Messenger\Messenger. This can be included into your code using the following shortcut.

$messenger = \Drupal::messenger();

This can be used to print messages to the user. For example, to print a standard message with a blue background do the following.

$messenger->addMessage('Message printed to a user.');

This can be done in one line like this.

\Drupal::messenger()->addMessage('Message printed to a user.');

There are four different types of message available, each of which is printed with other messages of the same type and on a different coloured background.

// Green status message.
$messenger->addStatus('Print a status to the user.');

// Blue message.
$messenger->addMessage('Message printed to a user.');

// Yellow warning message.
$messenger->addWarning('A warning about something!');

// Red error message.
$messenger->addError('An error happened!');

If you are in a Drupal 8 Form's submitForm() handler then you can also get access to the messenger service through the form object.

$this->messenger()->addMessage($this->t('Form message.'));

If you are still using drupal_set_message() then I recommend that you swap to the messenger service soon as it will be removed in future versions of Drupal.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.