0

Following is my .module file code

/**
 * Implements hook_user_presave().
 */

function cost_sheet_user_presave($account) {
    $source_userid = $account->id();
    \Drupal::messenger()->addMessage(t($source_userid));

}

This is giving me uid for already existing users when edited but not printing any value when a new user is created. How to get uid of newly created user in drupal 8 user presave hook?

5
  • Just check $account->isNew()
    – Jonh
    Aug 10, 2022 at 10:19
  • That is to check the account is new right ? How to get uid from newly created account ?
    – Rifas Ali
    Aug 10, 2022 at 10:24
  • 2
    A new user/any entity can not have an ID before being saved the first time
    – Hudri
    Aug 10, 2022 at 10:55
  • Ho yeah @hudri fair enough. So in that case I think I should use hook entity insert right ? Because I want to set users ( both added and edited ) in some other entities.
    – Rifas Ali
    Aug 10, 2022 at 11:02
  • First guess is: use hook_entity_postsave() instead
    – Hudri
    Aug 10, 2022 at 11:04

2 Answers 2

1

You can't get the user ID in hook_user_presave() for a new user because the ID isn't assigned until the user is saved.

So how do I run code that uses the user ID when saving a user, regardless of whether the user is new or has been edited?

Refactor your code that does something with the user ID into a function, doStuffWithUserID().

function mymodule_user_presave($account) {
  if (!$account->isNew()) {
    doStuffWithUserID();
  }
}

function mymodule_user_insert($account) {
  // The new account has been saved, so we have an ID.
  doStuffWithUserID();
}
1
  • Thanks I almost forgot that.
    – Rifas Ali
    Aug 10, 2022 at 11:04
0

The only hooks called after an entity is saved in the database are hook_ENTITY_TYPE_update() for updated entities, and hook_ENTITY_TYPE_insert() for new entities. Once the entity is stored in the database, its ID will have a value.

Unfortunately, Drupal core doesn't use any hook_ENTITY_TYPE_postsave() which would make sense as it uses hook_ENTITY_TYPE_presave().

This means that your module should implement cost_sheet_user_update() and cost_sheet_user_insert().

Keep in mind that EntityStorageBase::doPostSave() invokes either one or the other of those hooks. Their code doesn't need to check whether the entity is new.

// Allow code to run after saving.
$entity->postSave($this, $update);
$this->invokeHook($update ? 'update' : 'insert', $entity);

Your Answer

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

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