2

I'm new in Drupal 8 and I need to update the user when a node of a specific content type is created or updated. I did some searching and I find hook_entity_create but this hook Act when creating a new entity

2
  • node is an entity...
    – No Sssweat
    May 24, 2018 at 6:12
  • Yes I know that, but I need to update the user after the entity(node) is created - thank you for help May 24, 2018 at 6:17

3 Answers 3

3
/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function MYMODULE_node_insert(Drupal\node\NodeInterface $node) {

  if($node->bundle() == 'article') { //check for a content type, ex: article
    $user = \Drupal\user\Entity\User::load($uid); // load the user
    $user->set('field_name', $some_value); // set a value for a particular field
    $user->save();
  }

}

Originally I wrote:

MYMODULE_node_create(Drupal\node\NodeInterface $node) {

Changed it as per the comment below.

1
  • 3
    I wouldn't save anything to the database in this hook because you don't know if the entity form will be submitted. Use hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update).
    – 4uk4
    May 24, 2018 at 6:38
0

You can use Rules module (in alpha) to perform some actions after new content or updated content is saved.

0

I'm not sure that I clearly understand your needs, but the hook_node_presave lets you the option to take a different action if it's a new or an updated node. Of course, it is always a good idea to wrap it in a try catch.

/**
 * Implements hook_node_presave().
 * 
 * Acts on an node before it is created or updated.
 *
 * This hook is invoked from $node->save() before the node is saved to the
 * database.
 *
 * @param \Drupal\Core\Entity\EntityInterface $node
 *   The node that is being inserted or updated.
 *
 */
function MYMODULE_node_presave($node) {
  // If it is the wanted content type ...
  if($node->getType() === 'my_wanted_type') {
    // ... and if what you need is the current user ...
    $user = \Drupal::currentUser();
    // ... check if it is a new or an updated node
    $operation = $node->isNew() ? 'create' : 'update';
    // ... and call the function that will handle your needs.
    updateUserOnNodeSave($user, $operation);
  }
}

function updateUserOnNodeSave($user, $operation) {
  if(null != $user) {
    if($operation === 'create') {
      // do something meaningful with $user
    }
    elseif($operation === 'update') {
      // do something meaningful with $user
    }
    $user->save();
  }
}

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.