6

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).

  • Did you try 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; } } – Rockabelly Oct 14 '17 at 11:10
  • Of course, you might need to check if it is a new user $entity->isNew() or/and if the user has a specific role $entity->hasRole($rid). – Rockabelly Oct 14 '17 at 14:00
8

In an insert hook the user is already saved and should have an user id. So creating a node and assigning it to the new user as author should be no problem:

/**
 * Implements hook_ENTITY_TYPE_insert() for user entities.
 *
 * Adds a first node for a new user
 */
function mymodule_user_insert(\Drupal\user\UserInterface $user) {
  \Drupal\node\Entity\Node::create([
    'type' => 'XYZ',
    'title' => 'First node for user #' . $user->id(),
    'uid' => $user->id(),
  ])->save();
}

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.