When to use hook_update_N & hook_post_update_NAME?

When to use hook_update_N & hook_post_update_NAME?

On8th Feb 2022, 2025-01-20T16:50:58+05:30 ByKarthik Kumar D K | read
Listen Pause Resume Stop

In this article, we are going to learn when to use hook_update_N and hook_post_update_NAME. In general, I was using hook_update_N for any database-related changes or with any configuration additions or updates. And I was using hook_post_update_NAME for any content creation or updating or for the creation or updating any taxonomy terms etc, sometimes for clearing site caches as well.

But, let’s have a check like why Drupal is offering us these two features and what is the flow of execution of these two.

I have checked few core modules and a few contributed modules and understood that In a few of the modules there is no clear separation in the usage of these two hooks and in a few of the modules hook_update_N is used to modify field definitions and hook_post_update_NAME is used for creating or updating data.

I have gone through a few of the articles and documentations and understood that within hook_update_N it's better to do config or database related changes & in the hook_post_update_NAME it's better to do entity changes or content changes or something else.

To get to know more about about, had a check in the drupal core code and found the DbUpdateController class, in which triggerBatch method is doing the stuff on running https://drupal.local/update.php

  • Initially all hook_update_N are found here and on the basis of module name they are picked up into the batch.
  • Later hook_post_update_NAME are found and added to the batch. In case if any exist then all the caches are flushed at this point.

Also check the Drush, to understand how drush triggers this stuff. And UpdateDBCommands is the class, in which updateBatch method is doing the stuff on running drush updb.

  • Initially gets all the hook_update_N and sorts on the basis of module name and adds to the batch to process and flush caches.
  • In case if any hook_post_update_NAME exists, add all hook_post_update_NAME to the batch to process.

Small difference on running update.php and drush updb, its flushing caches during the process, apart from this else is the same.

Overall, it's not clear which one to use for what actions. And I see, better would be using hook_update_N for doing database changes or configuration changes and using hook_post_update_NAME for doing any entity changes or content changes. Let me know your thoughts in the comments.

Related Articles

Recent Articles

66% OFF
Ulla Popken Vestido para Mujer

Ulla Popken Vestido para Mujer

16.00 47.18

Recent Quick Read

Recent Great People

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies