drupal_set_message

drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE)

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.

See also

drupal_get_messages()

status-messages.html.twig

File

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

Code

function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  if (isset($message)) {
    if (!isset($_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type] = array();
    }

    // Convert strings which are safe to the simplest Markup objects.
    if (!($message instanceof Markup) && $message instanceof MarkupInterface) {
      $message = Markup::create((string) $message);
    }

    // Do not use strict type checking so that equivalent string and
    // MarkupInterface objects are detected.
    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type][] = $message;
    }

    // Mark this page as being uncacheable.
    \Drupal::service('page_cache_kill_switch')->trigger();
  }

  // Messages not set when DB connection fails.
  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
}
doc_Drupal
2016-10-29 09:03:20
Comments
Leave a Comment

Please login to continue.