Thursday, September 29, 2011

How the drupal_set_message() function works in Drupal?

First of all drupal_set_message() is used to show the notification to the user.
Notifications in 3 different ways
  1. status
  2. warning
  3. error

Example:

drupal_set_message("example for status message", 'status');
drupal_set_message("example for warning message", 'warning');
drupal_set_message("example for error message", 'error');

After the drupal_set_message() function intialized a message into it, it is actullay stored in SESSION variable.

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

    if (!isset($_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type] = array();
    }

    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type][] = $message;
    }
  }

  // messages not set when DB connection fails
  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
}
 
To display the message which is stored in the Session, Drupal using a 
function to achieve this.
 
theme_status_messages ()

function theme_status_messages($display = NULL) {
  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "<div class=\"messages $type\">\n";
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }
  return $output;
}
 
 
Finally, with one example...

/* Assigning the Notification message */
drupal_set_message("my testing message", 'warning');

/* Displaying the Notification message */ 
echo theme_status_messages();

No comments:

Post a Comment

Followers