2 min read

Drupal 7: Changing the execution order of hooks

Changing the execution order of hooks in Drupal is a fairly simple task. Sometimes, hook_form_alter from a specific module is executed before the module that adds elements to the form. In other cases, you may want to execute hook_init before any other module does. There are many situations where adjusting execution order is necessary, and this can be handled using hook_module_implements_alter.

Execute the hook last

function hook_module_implements_alter(&$implementations, $hook) {
  // Name of the hook.
  if ($hook != 'form_alter') {
    return;
  }
  $module = 'my_module';
  $group = $implementations[$module];
  unset($implementations[$module]);
  $implementations[$module] = $group;
}

Execute the hook first

function hook_module_implements_alter(&$implementations, $hook) {
  // Name of the hook.
  if ($hook != 'form_alter') {
    return;
  }
  $module = 'my_module';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);
  $implementations = $group + $implementations;
}