Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Hook into and Preprocess Drupal Messages

Category: 

So after the line dancing party at the pole barn in Corn County last night, I needed to prevent/hide Drupal messages from being displayed to certain user roles under certain conditions. Luckily Betty Sue, from Corn City, told me about theme_status_messages().

After copying theme_status_messages() into my theme's template.php file and renaming the function to mytheme_status_messages, I was ready to rock.

The following example hides all error/warning messages from anonymous users and user's who don't have the 'administer nodes' permission. You can easily add your own conditions to filter out which message types should be displayed to who.

function mytheme_status_messages ($display = NULL) {

  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {

    // skip all error/warning messages for anonymous users
    if (!user_is_logged_in() && ($type == "error" || $type == "warning")) { continue; }

    // skip error/warning messages for users who don't have the 'administer nodes' permission
    else if (!user_access('administer nodes') && ($type == "error" || $type == "warning")) { continue; }

    ...

Technically we aren't hooking in or preprocessing anything by Drupal definitions, we are actually themeing the messages the way we want, but I figured I'd include those keywords to help people get here and learn the goodness.

Don't forget to flush the theme registry and wash your hands when you're done.

Update: 2011-06-22 - I came across the module Disable Messages which appears to have a UI to do similar tasks. Haven't tried it out yet, but it has 6.x and 7.x versions, and is under active development. Rootin' tootin'!

Comments

Thanks! You'r post helped me to find solution of this problem: http://drupal.org/node/1043808#comment-5245710

Thanks for the tip!

Just an update for D7:

<pre>

function MYTHEME_status_messages ($variables) {

  $output = '';

  // skip all error/warning messages for anonymous users
  if (!user_is_logged_in() && ($type != 'status')) {
     return $output;
  }
  // default processing
  else {
    return theme_status_messages($variables);
  }
}

</pre>

Add new comment