When a checkout is completed by an anonymous user on a Drupal Commerce website, a Drupal account will be created. I would look to auto-assign a role like 'customer' to the newly created Commerce user. How can I do that programmatically? It has to be in Drupal 7 code so I can use it for my custom module.

1 Answer 1

$account = new stdClass;
$account->is_new = TRUE; //indicate the account is new
$account->name = 'account_name';
$account->pass = user_hash_password('password'); // make a function to create random passwords
$account->mail = 'email';
$account->init = 'email';
$account->status = TRUE; //set the user to activated at creation
$account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE); //set user as authenticated user
$account->timezone = variable_get('date_default_timezone', '');
$new_user = user_save($account); //create user (user_save() returns a fully loaded $user object)

$role_name = 'ROLE_NAME'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);

You can use the hook: hook_user_insert. And apply the last piece of code from above to update the role.

  • I think I have been unclear. Drupal Commerce already creates an account when the checkout is completed. Somehow I have to jump in, for example with a commerce hook and fetch the newly added user and edit the role there.
    – user5706
    Feb 21, 2012 at 10:12
  • You can use the hook: hook_user_insert. api.drupal.org/api/drupal/modules%21user%21user.api.php/… And apply the last piece of code from above to update the role.
    – dimitril
    Feb 21, 2012 at 10:18
  • Ah, yes. That sounds good. I'll let you know if it worked for me.
    – user5706
    Feb 21, 2012 at 10:22
  • I made an error in my thinking: all new users should be assigned the customer role. So this was my final implementation: hook_user_presave(&$edit, $account, $category) { if (isset($account->is_new) && !empty($account->is_new)) { $user_roles = user_roles(TRUE); $default_role = avariable_get('debtor_settings_default_role'); if (!isset($edit['roles'])) { $edit['roles'] = array(); } $edit['roles'] = array($default_role => $user_roles[$default_role]); } }
    – user5706
    Feb 21, 2012 at 12:41
  • 1
    @dimitril Consider adding what you report in your first comment in the answer itself. The answer should not be searched in the comments.
    – apaderno
    Feb 21, 2012 at 13:01

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.