1

Is there a way to prevent other preprocess hooks from being triggered?

I have a Drupal 8 hook_preprocess_HOOK() implementation, and I'm doing some alterations. There will be other modules with same hook, and I need the other preprocess hooks not to alter my changes to $variables.

The only options I have are:

  • Rely on weights system, which still could cause problems
  • Set a value inside $variables and prevent other modules from doing their thing if the variable is set

3 Answers 3

2

You can disable hooks via hook_module_implements_alter().

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_page') {
    unset($implementations['module_foo']);
    unset($implementations['module_bar']);
  }
}
5
  • It doesn't work with preprocess functions implemented by themes, though.
    – avpaderno
    Commented May 29, 2017 at 11:19
  • 1
    The OP asks for modules, so the response is accurate.
    – jonhattan
    Commented Jun 1, 2017 at 6:51
  • 1
    For themes, if the hook suggestions system is not enough, perhaps hook_theme_registry_alter() can do the job, by overriding the preprocess functions.
    – jonhattan
    Commented Jun 1, 2017 at 6:52
  • I am wondering why is is immposible to get debuger to stop and enter into MYMODULE_module_implements_alter function to inspect values?
    – Blissful
    Commented Jun 6, 2019 at 14:35
  • @MarkoBlazekovic it is because that function is called during cache clear and not page load. Try setting a breakpoint and clearing caches through UI. Commented Jul 22, 2019 at 3:51
1

Here's an implementation for Drupal 9 that makes MYMODULE_preprocess_image_style() run first:

/**
 * Implements hook_theme_registry_alter().
 *
 * Makes MYMODULE_preprocess_image_style() run first.
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  $themeKey = 'image_style';
  if (isset($theme_registry[$themeKey]['preprocess functions'])) {
    $fname = "MYMODULE_preprocess_$themeKey";
    $pf = &$theme_registry[$themeKey]['preprocess functions'];
    $index = array_search($fname, $pf);
    if ($index) {
      unset($pf[$index]);
      array_unshift($pf, $fname);
    }
  }
}
0

Preprocess hooks (and specifically hook_preprocess_page) are not subject to hook_module_implements_alter, even if they are implemented by modules. However, they can be adjusted by using hook_theme_registry_alter as suggested by @jonhattan above. Look in the $theme_registrary['page']['preprocess functions'] for the indexed array of implementations.

Note: Tested with Drupal 9.3.8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.