Order of alter hooks is not always respected by ModuleHandler

Created on 17 March 2020, almost 5 years ago
Updated 26 June 2023, over 1 year ago

Problem

The module handler does not respect the configured weight for extra hooks. I bumped into this issue when I tried to increase the weight of MY_MODULE in MY_MODULE_module_implements_alter() and run a hook_form_user_register_form_alter() and hook_form_user_form_alter() implementation after the ZZZ module's implementations. MY_MODULE's hooks were always run before the ZZZ module's hook implementations, although they should have been the last ones. (Your first guess would be that it caused by the alphabetical order, and you would not be wrong...)

This problem caused by the current impementation in \Drupal\Core\Extension\ModuleHandler::alter() which I beleive is overly complicated. In case of the described problem, it collects all base hook (hook_form_alter()) and all extra hook (hook_form_FORM_ID_alter() ) implementations, properly ordered by weights set by hook_module_implements_alter() implementations, then threw those ordered lists away and re-order the list alphabethically by doing this: $modules = array_intersect(array_keys($this->moduleList), array_merge($modules, $extra_modules));, then it calls hook_module_implements_alter()-s again only for the base hook (form) and re-orders the list. If your module's hook_module_implements_alter() does not change the weight of form_alter 's too - and for that the MY_MODULE_form_alter() function must exists, otherwise you get a RuntimeException - then your module's form id alters are not going to be called in the correct order.

Solution

Simplified the logic in the alter() function to do less magic but still call the base hook implementations first and if there is any implementation for the extra hooks, call them in the expected order too.

πŸ› Bug report
Status

Needs work

Version

11.0 πŸ”₯

Component
ExtensionΒ  β†’

Last updated 9 days ago

No maintainer
Created by

πŸ‡­πŸ‡ΊHungary mxr576 Hungary

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024