Checking if a user is in a role

For custom modules and well-defined roles, we sometimes want to check to see if a user is in the a particular role.

The easiest way to do so is to check the user's roles array:

global $user;

if (!empty($user->uid)) {
  if (in_array('desiredRole', $user->roles)) {
    // user is in role, perform desired actions here 
  }
}

The $user object is in the global name space, so using the global declaration in a function is necessary.

If the user isn't logged in, the $user->uid value will be 0. empty returns true for 0/null/empty values, as explained on php.net. in_array checks the desiredRole is in the user's roles.

Displaying content from one node in another

When writing custom drupal modules, I often want to include a blurb on the page about how to do a particular task on the page.

However, the phrases I use may not be the phrases or explanations another person would easily understand, given that I'm too close to the code.

The content of the blurb may change, too, as requirements change for the client.

Rather than hardcoding the text, making the client dependent on me for changes, I put the content into a node. In the custom module (e.g. the code I'm writing), I load the node and use the body of the node as the content to display.

  $node = node_load(array('nid' => '11363'));
  if (isset($node->body)) {
    $o .= $node->body;
  }

This has two requirements: the node exists, and the node has HTML included for formatting. Neither is typically a problem with the clients I have, but be sure to watch for the possibility the user is expecting filters to format the content before display.

Syndicate content