I have multiple roles on my website, and I want to assign a certain role to some users when they register to my site.

How can I assign a specific role to new users programmatically when they submit their registration forms?
I have tried modules like logintoboggan, autoassignrole, but they provide a default user role on registration, when I want to assign role to specific users, not to all users signing up on my site.

4 Answers 4


While you may not consider this to be "programmatic," you can use the Rules module to do this.

Install the module and create a new rule on the event "After saving a new user account." For the action, you will want to set the user role to ABC (where ABC are the role(s) you want to assign).

You can limit the role to specific users by adding conditions. For example, you can use the "Data comparison" condition to only apply the rule if the user has chosen a specific value on the registration form (detailed example: limit the rule to only those users who select "female" as their gender on registration).

You will have to create a rule for each condition/role combination you wish to award. However, Rules is a widely used module and can be exported manually or with the Features module, giving you a lot of flexibility.


We also solved this task with the user_multiple_role_edit() function. In our usecase we didn't react on the register-form but on a special menu-callback to create users on the fly.

First: Create a user

$user = new stdClass();
$user->name = $name;
$user->status = 1;

Second: Assign the user to the role

$role = user_role_load_by_name("my custom role");
user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);

This will make the default roles 4,5 and 6:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id){
    $form['account']['roles']['#default_value'][] = '4';
    $form['account']['roles']['#default_value'][] = '5';
    $form['account']['roles']['#default_value'][] = '6';

In my case there were only four profile2 profiles, but if the person was having a certain value in their registration form, I had to add them to a new role. Here is what I did:

function MYMODULE_user_insert(&$edit, $account, $category){
  if (array_key_exists('profile_club', $account)) {
    $is_uni = FALSE;
    if ($account->profile_club['field_uni_club']['und'][0]['value'] == 1 ) {
      $is_uni = TRUE;
    if ($is_uni) {
      $uid = $account->uid;
      $role_name = 'uni_club';
      if ($role = user_role_load_by_name($role_name)) {
        user_multiple_role_edit(array($uid), 'add_role', $role->rid);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.