Drupal 7: Execute code after insert, update, presave or save hooks

Published by Lennart Van Vaerenbergh on February 12, 2016

Hook_node_postsave(). I can almost see you smile while reading this hook function. *Snap*, get back to reality. It doesn't exist. But you might want to execute some code after a node is saved, which on its turn relies on the freshly saved node data.

Well, you can't use the regular node hooks such as hook_node_insert(), hook_node_update() and hook_node_presave(), because they are all executed within the scope of node_save(). That means that in those hooks, the new node data is not yet saved to the database. So any functions that rely on the new node data being in database, can't be executed here.

The solution to this situation is drupal_register_shutdown_function(). This function does wat it says. It registers a function name and its arguments for execution at shutdown, meaning when you Drupal request is almost finished. At this point, any nodes are saved to database and other core or contrib functions can use the data at will.

Source: http://www.webomelette.com/drupal-7-post-insert-hooks-shutdown-function

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
CAPTCHA
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.