Messages API

Last updated on
29 January 2024

Before Drupal 8.7.0 the only way to display status messages was the PHP API. Like this:

\Drupal::messenger()->addStatus(t('Successful message.'));
\Drupal::messenger()->addWarning(t('Warning message.'));
\Drupal::messenger()->addError(t('Error message.'));
drupal_set_message(t('Successful Message'), 'status');

But you have also the ability to do it easily via JavaScript.

Example

If you want to use JavaScript:

First add the Drupal core library core/drupal.message to your dependencies and clear the cache afterwards:

foo:
  js:
    js/foo.js: {}
  dependencies:
    - core/drupal.message

If you need to learn more about this approach, then read the following guide page: adding stylesheets (CSS) and JavaScript (JS) to a Drupal module. During JavaScript development, it is also recommended to disable caching.

Then use the core library in your JavaScript code:

const messages = new Drupal.Message();
const messageId = messages.add('test message');
messages.remove(messageId);
messages.add('test message', {type: 'warning'});
messages.add('test message', {type: 'error'});
// Clear ALL
messages.clear();

Messages will be added to the element with the attribute data-drupal-messages.

If you need to learn more about working with Javascript in Drupal, then check the guide page about the JavaScript API overview.

The result will look in your webbrowser like follows:

Drupal JavaScript messages API

Drupal core change record

Check if this feature is part of your Drupal core version (>= 8.7.0). Legacy Drupal core versions are not supported. This feature is part of Drupal core since the following change record: https://www.drupal.org/node/2930536. The core issue with the related maintainers discussion: Provide a common API for displaying JavaScript messages.

Help improve this page

Page status: No known problems

You can: