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*, 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 function scope of node_save() before any actual data saving. 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 what it says. It registers a function name and its arguments for execution at shutdown, meaning when your 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

Comments

Submitted by asdasd on Wednesday, March 13, 2019 - 16:24
sa
Submitted by Max on Tuesday, June 25, 2019 - 08:31
hook_node_insert(), hook_node_update() are executed after node is saved in DB right?
Submitted by Lennart on Tuesday, June 25, 2019 - 08:43
That is correct indeed.
Submitted by Max on Tuesday, June 25, 2019 - 09:00
"hook_node_insert(), hook_node_update() and hook_node_presave(), because they are all executed within the scope of node_save()" this line is little bit confusing. 

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.