You are here

function drupal_set_message in Drupal 8

Same name and namespace in other branches
  1. 4 includes/bootstrap.inc \drupal_set_message()
  2. 5 includes/bootstrap.inc \drupal_set_message()
  3. 6 includes/bootstrap.inc \drupal_set_message()
  4. 7 includes/bootstrap.inc \drupal_set_message()

Sets a message to display to the user.

Messages are stored in a session variable and displayed in the page template via the $messages theme variable.

Example usage:

drupal_set_message(t('An error occurred and processing did not complete.'), 'error');

Parameters

string|\Drupal\Component\Render\MarkupInterface $message: (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period.

string $type: (optional) The message's type. Defaults to 'status'. These values are supported:

  • 'status'
  • 'warning'
  • 'error'

bool $repeat: (optional) If this is FALSE and the message is already set, then the message won't be repeated. Defaults to FALSE.

Return value

array|null A multidimensional array with keys corresponding to the set message types. The indexed array values of each contain the set messages for that type, and each message is an associative array with the following format:

  • safe: Boolean indicating whether the message string has been marked as safe. Non-safe strings will be escaped automatically.
  • message: The message string.

So, the following is an example of the full return array structure:

array(
  'status' => array(
    array(
      'safe' => TRUE,
      'message' => 'A <em>safe</em> markup string.',
    ),
    array(
      'safe' => FALSE,
      'message' => "{$arbitrary_user_input} to escape.",
    ),
  ),
);

If there are no messages set, the function returns NULL.

Deprecated

in drupal:8.5.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead.

See also

drupal_get_messages()

status-messages.html.twig

https://www.drupal.org/node/2774931

1 call to drupal_set_message()
DrupalSetMessageTest::testDrupalSetMessage in core/tests/Drupal/KernelTests/Core/Common/DrupalSetMessageTest.php
The basic functionality of drupal_set_message().

File

core/includes/bootstrap.inc, line 506
Functions that need to be loaded on every Drupal request.

Code

function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  @trigger_error('drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \\Drupal\\Core\\Messenger\\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931', E_USER_DEPRECATED);
  $messenger = \Drupal::messenger();
  if (isset($message)) {
    $messenger
      ->addMessage($message, $type, $repeat);
  }
  return $messenger
    ->all();
}