Friday, January 24, 2014

Drupal 7 - specifying different output per role type in a template

Lot's of time I want content or links hidden for unauthenticated users but shown to the site administrators or other user roles. As I always forget how I do it, and then search in old code or ask my old friend mister Google, here's a little blog about how to:

In the template, for instance a field template for a field in a view, add this code.

// load the global user object
global $user;
// Check if  user has (f.i.) the 'administrator' or 'contributor' role.
if (in_array('administrator', $user->roles)||in_array('contributor', $user->roles)) {   
    // do something
} else {
   // do something else
}


NB! I use this on small sites. It is fast and easy.

For larger sites solution you should define these things using permissions, otherwise the site will in time become unmaintainable.  Adding a permission to another role might then mean changing twenty template files or so.


  // user_access default takes the current logged in user as user object
  if (user_access('permission x')) { 
    // do something
  } else  {
   // do something else
  }


Because setting up the normal permissions may become very complex, you can also add custom permissions with this module https://drupal.org/project/config_perms and use them in your template file for this kind of functionality.

No comments:

Post a Comment