[development] Assigning user to roles programatically -- what
finally worked
Rob Thorne
rob at torenware.com
Sun Jan 29 22:39:55 UTC 2006
Much thanks to Adrian and Khalid for their help on this.
It turns out that both of you are right, but for different code paths in
hook_user. Here's what seems to work in 4.6:
* On $op == 'update', Adrian is correct: the right way to do this
is to stuff the rid into the $edit structure ($edit['roles'][] =
$my_rid;)
* On $op == 'insert', Adrian approach doesn't work, because
user_save has already done everything it will ever do with the
user_roles table. So in that case, you need to do what Khalid
suggests: INSERT a row into the user_roles table.
Now that I'm doing both of these things, I'm getting correct behavior on
both registration of new users and update of existing users.
Thanks,
Rob
Adrian Rossouw wrote:
>
> On 27 Jan 2006, at 4:14 AM, Rob Thorne wrote:
>> 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?
>
> Just did this recently :
>
>
> ----- snip ---
> $user = user_load(array('uid' => $uid));
> $edit['roles'][] = _user_get_rid('administrator');
>
> user_save($user, $edit);
> ---- snip ---
>
> function _user_get_rid($name) {
> return db_result(db_query("SELECT rid FROM {role} WHERE name ='%s'
> limit 1", $name));
> }
>
>
> I needed to use the user api since I have more specific rules that I
> check for.
> IE: you can be one of the following 3 roles, in a certain order of
> preference, but never
> more than one.
>
>
> --
> Adrian Rossouw
> Drupal developer and Bryght Guy
> http://drupal.org | http://bryght.com
>
>
>
More information about the development
mailing list