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?
-
I think I know what you are going for - might want to check the answers here first. drupal.stackexchange.com/questions/183477/…– KevinCommented 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.– Pantelis NatsiavasCommented Jan 14, 2017 at 18:05
Add a comment
|
1 Answer
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()) {
// ...
}
}
-
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
-
1Yeah 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