3

I've been searching for this for ages, but could not come with a solution. Drupal 7 provided a way to get the uid of a newly created user after running user_save; the new user has been added and the uid has been returned in the object. However, now in Drupal 8 when I use the User::create() method, it only returns a constant based on whether the user has been created or updated. Is there any way to get the uid after the user has been created though? I don't seem to find a way. Any help is appreciated.

6

Where are you creating the user? Could you use entityTypeManager and EntityStorage instead of User::create()? I have the following in a method in a custom entity:

$storage = $this->entityTypeManager()->getStorage('user');
$owner =  $storage->create(['mail' => $email, 'name' => $this->getName()]);
$owner->save();
$uid = $owner->id();

If you don't have access to entityTypeManager() in your class, you could alternatively use:

$storage = \Drupal::service('entity_type.manager')->getStorage('user');
  • 2
    Yes, this is the right code to get the id. But the problem is not User::create(), it's that you need to save before you can get the id. – 4k4 May 11 '17 at 21:56
  • Thanks for the info! Good to know...I've never used the User::create() method. – user72086 May 12 '17 at 0:16
  • Well, I do call the save method after calling the User::create(), i.e. User::create()->save() and that returns the SAVED_NEW or SAVED_UPDATED constant based on what action is performed. It's written in the method comments. – crzpiot May 12 '17 at 5:10
  • 2
    The problem was that the methods cannot be chained. You have to call User::create() and then I was assigning the result of the save() method to the same variable that was previously populated with the new entity object. If you do not chain the methods, both mine and the above specified methods work. Thanks a lot. – crzpiot May 12 '17 at 5:20
0

To get the ID from User::create(); use the id() function after the save() function:

$user = \Drupal\user\Entity\User::create();
$user->setPassword(user_password());
$user->enforceIsNew();
$user->setEmail($user_data['user_email']);
$user->setUsername($name);

//Save user
$res = $user->save();
//$res returns the SAVED_NEW or SAVED_UPDATED constant no good for an ID

//But the id function should pass the newly created ID
$newid = $user->id();

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.