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.

3

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();
    }
}
1

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.

  • 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 Nov 20 '17 at 6:45
  • In hook_node_presave() after setting the value on a field also add $node->save(). – OPTASY Nov 20 '17 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 Nov 21 '17 at 5:40

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.