I want to create a single node of content type XYZ for each user upon registration.
I tried to use hook_user_insert()
(hook_entity_insert()
), but this doesn't work because when I set the nid to the uid, the uid is still 0 (anonymous user), and the node needs to be assigned to the newly created account. (NOTE: This was my misunderstanding, see below.)
I want to create the nodes upon account creation because each user should have only one node of this content type.
In Drupal 7, I managed to do this in Rules using a rule set in which I saved the user account and then created the new node. Since Rules isn't in beta for Drupal 8 yet, I am trying to do this programmatically.
Here is the code I am using:
function MYMODULE_user_insert(Drupal\Core\Entity\EntityInterface $entity) {
$user = \Drupal::currentUser();
$profile = Node::create(['type' => 'userprofilenode']);
$profile->set('uid', $user->id());
$profile->enforceIsNew();
$profile->save();
As noted in 4k4's answer, $entity already has a UID. The problem is that I mistakenly introduced the current user, which is 0 (anonymous).
hook_entity_presave()
? Something like this/** * Implements hook_entity_presave(). */ function my_module_entity_presave($entity) { if (($entity instanceof UserInterface) { $uid = $entity->id(); ... } else { return; } }
$entity->isNew()
or/and if the user has a specific role$entity->hasRole($rid)
.