Tuesday, June 29, 2010

Checking whether a user has a specific role...

Drupal 6 makes it easy to check whether or not a user has a specific Access Privilege.  It is indeed used in most modules, as it is essential and yields much power and flexibility in use.

What Drupal 6 does however NOT make trivial, is to check whether or not a user has specific role ( a named role, e.g. "administrator", "authenticated", "member" - whatever roles you may use).
How-to
<?php  global $user;

 
// Check to see if $user has the administrator role.
 
if (in_array('administrator', array_values($user->roles))) {
   
// Do something.
 
}?>

Here we use the default full array that each user has as an attribute - the collected roles of the user!  Note that this array is keyed, and the role names (not unique!) are thus kept in the values of the keyed array!
Why is this useful?
Well, let's suppose that you have a list of nodes (a blog-style for example), and these nodes in the listing are authored by different users - different users with different roles indeed!  Using the technique above, will enable you to theme the blog-entries of each user-role, making it easier to visually tell them apart on-page for the reader of the blog.

No comments:

Post a Comment