[ACCEPTED]-Post-save callback?-drupal-7
Currently Drupal core does not offer any 11 hook to do actions after a node/entity is 10 inserted/updated/deleted in Database. For 9 example, you can not send an email mentioning 8 the node after the node is inserted because 7 Drupal uses SQL transactions and the node 6 is not yet fully written to database when 5 hook node presave is called so if for any 4 reason the transaction is rolled back, users 3 will receive a false mail.
So Hook Post Action module introduces 2 several new Drupal hooks to overcome this 1 limitation:
- hook_entity_postsave
- hook_entity_postinsert
- hook_entity_postupdate
- hook_entity_postdelete
- hook_node_postsave
- hook_node_postinsert
- hook_node_postupdate
- hook_node_postdelete
The hook has not been removed but splitted 2 up into separate hooks for each $op.
See: http://api.drupal.org/api/search/7/hook_node
For 1 post-save, you want hook_node_insert() and hook_node_update()
I suppose hook_entity_presave
could be the hook you're looking 5 for, if you want to act before your node 4 is updated :
Act on an entity before it is 3 about to be created or updated.
Or, if 2 you prefer acting after it's updated, take 1 a look at hook_entity_update
:
Act on entities when updated.
Just to complete this a bit more and if 7 you need to perform any operation after 6 the node has been saved/updated you can 5 use the module @sina-salek has recommended 4 you or you can use this code:
// Same for hook_node_save!
function my_module_node_update($node) {
if ($node->type == 'content_type_name') {
// Invoke your callback function AFTER the node is updated.
drupal_register_shutdown_function('_my_module_the_function_to_call', $node);
}
}
function _my_module_the_function_to_call($node) {
// do stuff...
}
By using the 3 drupal_register_shutdown_function you are making sure to call your custom 2 function when the hook has finished and 1 the node has been persisted on the DB.
Another way this can be achieved is by extending 10 the Node entity with your custom class and 9 calling your code inside the Node::postSave
method. This 8 method will get called when node gets saved 7 or updated.
You specify your custom extended 6 class by implementing hook called hook_entity_type_build
and provide 5 your new class, e.g.: $entity_types['node']->setClass(NodeExtended::class)
Inside your class 4 you than override postSave
method. I usually just 3 dispatch my custom event here so other modules 2 can subscribe to this node post save event, but 1 that's another topic.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.