Modifying a Node before/after it is saved in Drupal 7

To modify a node before it is saved to the database, use the hook_node_pressave() function

php
function yourmodule_node_presave($node) {
if ($node -> type == "article") {
....
}
}

To react to a node after it has been saved, use the hook_node_update() and hook_node_insert() functions

“`php
function yourmodule_node_save($node) {
if ($node -> type == “article”) {
….
}
}

function yourmodule_node_insert($node) {
    return yourmodule_node_save($node);
}

function yourmodule_node_update($node) {
    return yourmodule_node_save($node);
}```

There is also equivalent hook_entity_presave(), hook_entity_update() and hook_entity_insert() functions.

Note:

  • The $node passed in after the database has been updated is the OLD may have been changed by the database
  • The old values are accessible through the $node -> old variable

Leave a comment

Your email address will not be published. Required fields are marked *