7

Is there a hook which could be used to execute code when a specific field of a custom content type is updated? Is there a specific hook, or should I use hook_node_presave()? In that case, how could I check that the field's value has indeed been modified?

2
  • I think I know what you are going for - might want to check the answers here first. drupal.stackexchange.com/questions/183477/…
    – Kevin
    Commented Jan 14, 2017 at 17:58
  • @Kevin thank you very much for your time. However, this question does not refer to creating a new node. It refers on updating a node's field. Commented Jan 14, 2017 at 18:05

1 Answer 1

11

Using hook_entity_presave():

You can get the original entity object from $entity->original when it is an update of the entity.

So something like this ought to work:

function foo_node_presave(\Drupal\node\NodeInterface $node) {
  if (!$node->isNew() && $node->get('field_bar')->getValue() != $node->original->get('field_bar')->getValue()) {
    // ...
  }
}
2
  • Thank you very much for your answer. I checked it and works as expected. I have a minor question though... I would expect the hook function's name to be foo_entity_presave and not foo_node_presave. Am I missing something here? While I cannot find the hook_node_presave in the drupal 8 API documentation, it seems that the function foo_node_presave is working. Do I miss something regarding the hook functions naming conventions? Commented Jan 15, 2017 at 14:39
  • 1
    Yeah it's just another naming convention, I probably should have linked you here as well: api.drupal.org/api/drupal/…
    – Clive
    Commented Jan 15, 2017 at 15:28

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.