hook_update_N or hook_post_update_NAME

Matt Glaman
5 min readJan 12, 2022

Today I realized that I had no idea when it was appropriate to use hook_update_N or hook_post_update_NAME. I have ideas, but I was not sure about the concrete reasons. My gut instinct is that hook_update_N is for schema and other database-related changes. And, then, hook_post_update_NAME is for configuration changes and clearing caches once the schema changes have been finished.

But is that true? Does Drupal core follow this pattern? Finding examples in Drupal core was also tricky; I had to switch back to the 8.9.x branch to get a good collection of references.

  • The Views module is a mixed bag. There are configuration updates and changes to View entities in both update hooks, with no real differentiation or understanding of why.
  • The Workspaces module has a decent separation. It uses hook_update_N to modify field definitions, which are schema. Then it uses hook_post_update_NAME to perform some data manipulation... but it also manipulates the database schema here.

Maybe part of the reasoning is to handle different stages. I know I have experienced some oddities when executing various hook_update_N in sequential order – purposely making two update hooks at once, so they run after each other. But that was mainly in Drupal 7 days.

The “Improve documentation for post update hooks and update hooks to clarify distinction” issue on Drupal.org. jibran posted this as his guide:

  1. post-update hooks run right after update_N hooks.
  2. update_N hooks are used when config or DB schema needs CRUD
  3. post-update hooks are used to update config entities, can be used for CRUD content entities but not recommended as site config might need and update see… [other issue.]

https://www.drupal.org/node/3034742 is a very good resource to understand the recommended way to install/update/uninstall entity types/fields in the update hooks.

The other issue is a length detail on some quirks when updating configuration during update hooks: https://www.drupal.org/project/drupal/issues/2901418. The last link he refers to is the change record for when automatic entity schema updates were removed. Unfortunately, it does not clear up the decision for me. Just “I need to do X first, and Y second. So I will use the two different hooks.”

Support for automatic entity updates has been removed

--

--

Matt Glaman

PHP software engineer, open source contributor, and speaker