0

When a new user is created, either via admin or by normal user registration, I need to assign a custom role to that user. It works fine, but I'm not convinced I've checked the user status enough.

In my hook_user_presave() implementation, I check to make sure the administration role isn't set, and uid isn't 1. To set my role:

if ($account->uid == 1 || array_search('administrator', $account->roles))
        return;

$account->roles[] = 'my_custom_role';

I only want to do this if it is a brand new user being created/inserted. The documentation says hook_user_presave() is called if the user is being updated. What is the best way to check if this is a brand new user creation? Would uid be set to 0?

2

The documentation for hook_user_presave() says the hook is invoked when an user account is updated, or created, not just when the user account is updated.

If you look at user_save(), you will notice that $account->is_new is set before invoking hook_user_presave(), when the user account is being created. If the account is being updated, $account->is_new is not set, and $account->original contains the user object before any changes.

In Drupal 8, $user->is_new will be replaced with Entity::isNew().

1

It looks like the $account->is_new flag is how to test. I've been testing and it seems to be the way to go.

1

hook_user_presave() is fine, just pay attention to $account->is_new. And save fields in the $edit variable in the usual format, ex:

if ($account->is_new) {
  $edit['field_time'][LANGUAGE_NONE][0]['value'] = (string)time();
}

$edit is passed as reference and so you don't need to do anything else.

0

Try hook_user_insert which is called only when saving a new user. Also, make sure that $account->uid is set. If uid is set, that means some save function( user_save() ) is called before.

Also, try in_array() instead of array_search. You just wanted to check if the role is in the array, which in_array does out of the box.

  • I looked at hook_user_insert(), but that is called after the insert. If there was a quick API function I could call to pass a UID and roll id, then that would work as well. – vintorg Jul 22 '12 at 1:30
  • Yes.. so you have the uid there. Also, make sure that you pass $account by reference (&$account) or your changes won't get saved. – AyeshK Jul 22 '12 at 3:29
  • What is a quick API call to set a role to a user? I couldn't find one. – vintorg Jul 23 '12 at 3:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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