1

I want to update an field in hook_entity_insert(). The following code doesn't work.

$entity->field_range->value = 'test';
$entity->save();

I also tried loading from node object, but still it doesn't work.

$node = \Drupal::entityManager()->getStorage('node')->load($entity->id());
$node->set('field_range', 'test');
$node->save();

After inserting the node only I will get the text "test" dynamically and it won't work in hook_entity_presave().

Any help on how to update an field on hook_entity_insert will be nice. Thanks in advance.

2 Answers 2

4

From this solution we can able to do like below to update an field on hook_entity_insert

$entity->field_range->value = 'test';
drupal_register_shutdown_function('_cc_custom_post_insert',$entity);

function _cc_custom_post_insert($entity) {
    if($entity) {
        $entity->save();
    }
}
2

You can use hook_ENTITY_TYPE_presave as in hook_ENTITY_TYPE_update

When saving existing entities, the entity is assumed to be complete, partial updates of entities are not supported.

use Drupal\node\NodeInterface;

function mymodule_node_presave(NodeInterface $node) {
  switch ($node->getType()) {
    case "article":
      $node->set('field_range', 'test');
      break;
  }
}

Here no need to load node.

3
  • Hi Ajay , I have edited the questtion, After inserting the node only i will get the text "test" dynamically and it wont work in hook_entity_presave().
    – Ram
    Commented Nov 20, 2017 at 6:45
  • In hook_node_presave() after setting the value on a field also add $node->save().
    – OPTASY
    Commented Nov 20, 2017 at 18:11
  • 1
    I really don't think so there $node->save() is necessary. As hook, itself reveals that "presave" and it will save the respective entity as we pass all values.
    – Ajay Reddy
    Commented Nov 21, 2017 at 5:40

Your Answer

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

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