Early Bird Registration for DrupalCon Portland 2024 is open! Register by 23:59 UTC on 18 March 2024, to get $100 off your ticket.
By vijaycs85 on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
7.x
Introduced in version:
7.36
Issue links:
Description:
#2394517: Add a function to check if a user has a certain role has introduced a new API function to check if a user has a specific role.
Before:
function MYMODULE_foo() {
global $user;
$role = user_role_load_by_name('Author');
$has_role = isset($user->roles[$role->rid]);
if ($has_role) {
// Code if user has 'Author' role...
}
else {
// Code if user doesn't have 'Author' role...
}
}
After:
function MYMODULE_foo() {
$role = user_role_load_by_name('Author');
if ($role && user_has_role($role->rid)) {
// Code if user has 'Author' role...
}
else {
// Code if user doesn't have 'Author' role...
}
}
Impacts:
Module developers
Comments
I do think this is better now
I do think this is better now.
Testing :)
Rewarded work .
previous implementation
I have always used
in_array('xxxxx', $user->roles)
.Is there a reason why the new implementation would be better?
Thanks,
- Perry
If role does not exist...
It should be...
+1 to pelowe
Hi, @Cinedin
Hi, @Cinedin
I'm updated change record.
Illegal offset type in isset() error
A quick dpm() reveals that the parameter $rid is an array instead of an integer, raising an error in the function implementation.
Sticking on drupal 7.35 for now
Any idea why ?
Can we use role name instead of role id?
It’s really good to see the new function to check a user have specific role or not.
I have a concerns here, Instead of checking role id we can check role name because am not sure we may have same data entry in roles table in development and Production servers(if records miss match it will give wrong matches with role id).
Changes :
function user_has_role($role_name, $user = NULL) {
if ($user == NULL) {
global $user;
}
if (is_array($user->roles) && in_array($role_name, array_values($user->roles))) {
return TRUE;
}
return FALSE;
}
Passing role-name is a good
Passing role-name is a good idea.
Regards,
tssarun.
Yeah, this should've been by
Yeah, this should've been by role name.
check by role name
I would love this!! Did anything ever come of this suggestion? As far as I can tell, user_has_role() is still just by role ID. Was the idea picked up in a different thread, or?
Handy role check function
You might find this utility function handy...
Example use...
Hi
Hi
Your function will not work. Because:
need update to:
Or update general function to: