On this page
Messages API
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.messageIf 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 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
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.