[development] Assigning user to roles programatically

Rob Thorne rob at torenware.com
Fri Jan 27 02:39:28 UTC 2006

Khalid B wrote:
> On 1/26/06, Rob Thorne <rob at torenware.com> wrote:
>> I'm looking for some way to assign a user to a role programatically.
>> You'd think this would be easy to do, but it isn't:  I tried just about
>> every drupal hook you can think of to hook add this to the "user add"
>> and "user edit" screens, and nothing worked.  The problem was that
>> node_save really really really wanted to get in there last, and I never
>> found a way to get around this.  I even tried to stamp the fields into
>> the database.  No use.  node_save just went in at the end of the request
>> and changed it back for me :-(
>> Does anyone know how to coerce Drupal 4.6 into doing this?  Or sweet
>> talk it into this?  It would be nice if there was an API for this, but
>> AFAIK there isn't.  What hook should I use, and which 2x4 do I need to
>> apply?
> Here are two functions that I used for a customer project that do just that:
> function mymodule_role_join($uid, $rid) {
>    db_query("INSERT INTO {users_roles} (rid, uid) VALUES ('%d',
> '%d')", $rid, $uid);
> }
> function mymodule_role_leave($uid, $rid) {
>   db_query("DELETE FROM {users_roles} WHERE rid = %d AND uid = %d", $rid, $uid);
> }

Much thanks.  Although...

I'm taking it that you don't tie this into the regular user add process, 
however....  since I've tried that approach already.  You write the 
entry into user_roles, and node_save helpfully deletes your records for 
you immediately after :-(

When do you call these functions?  As part of which hook?  I had tried 
to add it to the "user add" admin page using hook_user, but as Yoda once 
said, "Work it did not".


More information about the development mailing list