You are here

#DrupalGotcha: Update hooks run for disabled modules too

Submitted by Dave on 24 July 2015 - 2:16pm

A common gotcha I see with contributed modules is writing update hooks, using functions and APIs available from the module.


/**
 * Update all hipster things to no longer be trendy.
 */
function hipster_update_7100() {
  $things = hipster_thing_load_all();
  foreach ($things as $thing) {
    $thing->is_trendy = FALSE;
    hipster_thing_save($thing);
  }
}

In Drupal 7 and below, if your module was enabled at one point, is now disabled but not yet uninstalled, then its update hooks are still run! This means that in our example above, the functions hipster_thing_load_all() and hipster_thing_save() are undefined. GOTCHA!

Use module APIs as little as possible

If you are interacting with database data, use the direct database APIs instead of module APIs to avoid issues. This is the most fool-proof way to avoid any update hook issues.


/**
 * Update all hipster things to no longer be trendy.
 */
function hipster_update_7100() {
  db_update('hipster_thing')
    ->condition('is_trendy', 0)
    ->execute();
}

Load necessary files manually

If you do need to use a module function or API, you will need to load the files that contain everything you need to call. Take care to also check for other files that would need to be included by the functions you call yourself!


/**
 * Update all hipster things to no longer be trendy.
 */
function hipster_update_7100() {
  // Load hipster.module, which contains the hipster_thing_load_all().
  drupal_load('module', 'hipster');
  // Load hipster.things.inc, which contains hipster_thing_save().
  module_load_include('inc', 'hipster', 'hipster.things');
  ...
}

What about Drupal 8?

Drupal 8 removed the "disabled but not uninstalled" module state. If your module is not enabled, it means it is not installed; therefore it will not have its update hooks run. So no need to check for these gotchas if you are writing Drupal 8 modules!