Hello,

Is there a good way to test if the currently logged in user belongs to a role called Trade?

I know this will let me test if they're logged in...

if ($logged_in) {

Thanks for your help, N

Comments

uzbekjon’s picture

User object has roles array with role id as a key and role name as its value.

global $user;

$user->roles[ ROLE_ID ] = ROLE_NAME;

-------------------------------
Drupal Howto's and tips at Drupal HowTo Resouce
jQuery howto's and tips at jQuery HowTo Resouce

monkfish4d’s picture

Thanks for your reply...

I'm also new to PHP but I'm guessing that the $user->roles is an Array?

Is there a command to loop through it and test is Trade exists in there?

Thanks,
Nick

p.s. I'm thinking I need to be asking these Q's on a PHP forum? :)

barrett’s picture

No need to iterate through the array. You can use php's in_array function to do it for you:

if (in_array("TRADE", $user->roles)) {
  ...do something...
}

or you can search on the Role ID using array_key_exists

if(array_key_exists(<<the number of your Trade role>>,$user->roles)) {
  ...do something...
}

uzbekjon’s picture

Sorry double post.

It seems that we don't have "delete own comments" permission :)

Gabriel R.’s picture

What you want is:

  global $user;

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

Thanks to http://www.bywombats.com/blog/ryan/10-25-2007/checking-if-drupal-user-ha...