欢迎各位兄弟 发布技术文章
这里的技术是共享的
Here are some quick code examples that I have used to add or remove user roles in Drupal 6. This can be very helpful if you are building a module for a specific site that has to manipulate user roles. Using this technique is not the most flexible solution as it limits itself to the roles configured on a specific site (based on role id and role name). However, you could easily add a database table and an administration section and make this more flexible if needed.
Here is an easy way to add a role:
//you will need to enter the uid of the user here, I am just using user 1 $user = user_load(1); //first we check if the user has the role in question (using the rid of the role) if (!isset($user->roles[7])) { //if not we add the role and set the role name based on what is entered //in the drupal role administration section $user->roles[7] = 'role name seven'; }
Here is an easy way to remove a role:
//you will need to enter the uid of the user here, I am just using user 1 $user = user_load(1); //first we check if the user has the first role in question if (isset($user->roles[8])) { //if so, we unset the role unset($user->roles[8]); $edit = array('roles' => $user->roles); user_save($user, $edit); }
Here is an easy way to do a role swap:
//you will need to enter the uid of the user here, I am just using user 1 $user = user_load(1); //first we check if the user has the first role in question if (isset($user->roles[8])) { //if so, we unset the role unset($user->roles[8]); //now we check to see if they have the role we want to swap for if (!isset($user->roles[7])) { //if not we add this role $user->roles[7] = 'role name seven'; } $edit = array('roles' => $user->roles); user_save($user, $edit); }
Helpful? Let me know.
来自 http://codekarate.com/blog/programmatically-adding-or-removing-user-roles-drupal-6
Discussions
unset all roles
Thanks for this. If I want to clear the users existing roles and add new ones (may be the same or not). Is it okay to unset the whole roles array unset($user->roles); and then add new roles: $user->roles[9] = '02 member'; or is it a bad idea to unset the whole roles array?
Thanks.
Dave.
Test it
I have not tried unsetting the array but I am sure it would work fine as long as you make sure you set back the roles that you want the user to have.
Short answer... it should be fine, long answer.. I would test it thoroughly just in case.
The more important thing is that I would wonder why you need the functionality to clear all the users roles. If you have a valid use case, then I see no reason not to unset the array to clear out the users roles.
Thanks for the comment.
API
There is useful API function user_multiple_role_edit($accounts, $operation, $rid)
See http://api.drupal.org/api/drupal/modules!user!user.module/function/user_multiple_role_edit/6
Post new comment