Adding roles to users on account creation

Adding roles to users on account creation

Submitted by Priya Ganesan on Sat, 03/03/2012 - 15:31
Drupal logo

On one of the Drupal 6 projects we had the need to assign a specific role to all users who create their own account (by visiting 'user/register'). Let's say the role is 'abc' and the role id (rid) is 3. So every new user should have the 'abc' role automatically. After much reseach I found the winning formula :-)

The obvious part is that we have to implement the hook_user in a custom module. But what 

is not obvious is which $op to attach to, and then which of the parameters to manipulate and how. Here's the code for my implementation.

function mymodule_user($op, &$edit, &$account, $category = NULL){
  global $user;
  // if the user is anonymous and creating a new account.
  if($op == 'insert' && $user->uid == 0) {
    $edit['roles'][3] = TRUE;

In the above code, the name of my module is 'mymodule' and it is implementing the hook_user. Inside the hook, we access the $user global to check that the current user is anonymous ($user->uid == 0), so that we do not interfere with an administrator creating a new user and choosing roles for them. The $op we attach to is 'insert' because that is the $op executed when a new account is created. The trickiest part of all is the fact that instead of manipulating the $account param, or even calling user_multiple_role_edit, we manipulate $edit because that is the data that is being persisted to the database. Also, the structure of roles within $edit is peculiar, in that it needs use the role id (rid) as the index and boolean TRUE as the value, in order to assign a role to the user.

Hope someone finds this useful.


Priya Ganesan

Profile picture for user Priya Ganesan
Sr. Member of Technical Staff
  • Advanced knowledge of Drupal 6 & 7 configuration and module development
  • Well-versed in databases, reporting
  • Advanced knowledge of Ubercart, CiviCRM, Views, Migrate and other Drupal subsystems