How to get the currently logged in user's role in Drupal 7 ? Do you know a simple way of accomplish this ? Is there some drupal core functions for this?
You can access to the user roles by just using this PHP snippet:
<?php $GLOBALS['user']->roles; ?>
$user->roles is an array of the roles that belong to the user keyed by the role ID, value is the role string. So if you wanted to check if user had role 'authenticated user' your code snippet would look something like this (not necessarily the most optimized approach, in_array is a fairly performance-expensive function):
global $user;
if (in_array('authenticated user', $user->roles)) {
//do stuff here
}
Note that in_array can also accept an array as the "needle" (argument #1) so you could check against multiple role options:
in_array(array('authenticated user', 'anonymous user'), $user->roles);
You can access to the user roles by just using this PHP snippet:
<?php $GLOBALS['user']->roles; ?>
I have found a interesting solution to check for multiple roles of a user:
global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
if (empty($check) ? FALSE : TRUE) {
// is admin
} else {
// is not admin
}
// Load the currently logged in user.
global $user;
print_r($user->roles);//this gives you current user roles
//to check whether he is administrator, you can do so by
if (in_array('administrator', $user->roles)) {
// do some stuff
$form['field_end_date']['#disabled'] = FALSE;
}
© 2022 - 2024 — McMap. All rights reserved.
in_array
to check to see whether or not$user->roles
contains an array ofarray('authenticated user', 'anonymous user')
, not the individual elements'authenticated user'
or'anonymous user'
. array_intersect() would do the trick for that though. – Stele