[development] Assigning user to roles programatically

Khalid B kb at 2bits.com
Fri Jan 27 02:22:58 UTC 2006


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);
}


More information about the development mailing list