Skip to Main Content
Menu
Close Menu

Updating deprecated drupal_set_message() calls in Drupal 8

Summary

This covers only the most common use cases.

Replace: 

drupal_set_message('example message');

With: 

\Drupal::messenger()->addStatus('example message');

A little more information

If you are setting an Error, Status, or Warning, use

Replace:

drupal_set_message('example error', 'error');

drupal_set_message('example status', 'status');

drupal_set_message('example warning', 'warning');

With:

\Drupal::messenger()->addError('example error');

\Drupal::messenger()->addStatus('example status');

\Drupal::messenger()->addWarning('example warning');

If you are replacing usage in a class

You can use the Messenger trait. Add a use statement to the top of your PHP file:

use Drupal\Core\Messenger\MessengerTrait;

Add a use statement within your class

use MessengerTrait;

And then use the class property messenger().

Replace

drupal_set_message('example message');

With

$this->messenger()->addStatus('example message');

More examples

We have a set of examples as part of the Drupal Rector rector_examples module. See https://github.com/palantirnet/drupal-rector/tree/master/rector_examples.

Automating updates with Drupal Rector

Drupal Rector is an open source tool built using Rector which can help automate this deprecation as well as other common deprecations.

For more information, see https://github.com/palantirnet/drupal-rector.

What is covered by the rector

Drupal Rector currently replaces static calls to drupal_set_message() as shown above.

If a class has the MessengerTrait trait already, the property will be used as shown above.

Improvement opportunities

Drupal Rector does not add the MessengerTrait trait to classes that do not have it.

Drupal Rector does not handle cases where the type of message is passed as a variable. For example, drupal_set_message('my message', $type).

Drupal Rector does not inject the Messenger service into classes. The trait is a similar, but not a direct substitute for dependency injection.

Deprecation background

drupal_set_message used a global method call rather than a service. This makes unit testing more difficult. See https://www.drupal.org/project/drupal/issues/2278383 for further details.

References

The Drupal change record for this deprecation is available at https://www.drupal.org/node/2774931

Credits and thank yous

Thank you to Dezső Biczó for the original rector which was included in Drupal 8 Rector. Most of this rector was used as the basis for the one included in Drupal Rector.

Thank you to Dan Montgomery for leading Drupal Rector development to support this deprecation.

Thank you to Palantir.net for sponsoring this development.

Let's work together.

Have an exceptional idea? Let's talk and see how we can help.
New Call-to-action