[development] Assigning user to roles programatically

Adrian Rossouw adrian at bryght.com
Fri Jan 27 08:18:36 UTC 2006

On 27 Jan 2006, at 4:39 AM, Rob Thorne wrote:

> 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".

The problem with doing it as part of the user hook is that it saves  
at the very end of the hook. and one of the things the user hook does  
is delete all the roles and then
add only the new ones.

You can still modify the $edit variable and change what was 'actually  

function module_user($op, &$edit, &$user) {
     switch ($op) {
       case 'insert' :
         $edit['roles'][_user_get_rid('administrator')] = '';
         $edit['roles'] = array_flip(array_keys($edit['roles'])); //  
I am not sure it's strictly necessary, but it maintains the format  
that the modules are expecting, so it can't hurt

function _user_get_rid($name) {
   return db_result(db_query("SELECT rid FROM {role} WHERE name ='%s'  
limit 1", $name));

Adrian Rossouw
Drupal developer and Bryght Guy
http://drupal.org | http://bryght.com

More information about the development mailing list