Drupal 8 Messenger Service

7th February 2019

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.

$messanger->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.

  1. // Green status message.
  2. $messenger->addStatus('Print a status to the user.');
  3.  
  4. // Blue message.
  5. $messenger->addMessage('Message printed to a user.');
  6.  
  7. // Yellow warning message.
  8. $messenger->addWarning('A warning about something!');
  9.  
  10. // Red error message.
  11. $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.