6

I have implemented hook_menu_alter() in a module I have created. I have printed something inside that function call but nothing shows up, though the function hook_init() is executed from the same module. The output of hook_init() shows up in the page, but not from the hook_menu_alter() even after clearing the cache.

Does anybody have any idea regarding this issue?

function mymodule_init(){
print "here";
}

function mymodule_menu_alter(&$items) {
print "I am here";
return $items;
}

3 Answers 3

10

hook_menu() and hook_menu_alter() are not always invoked; they are invoked only when Drupal rebuilds the menus, such as when a module is enabled, disabled, installed, or uninstalled, or when the Drupal cache is cleared.

Anatomy of hook_menu reports the following sentence:

hook_menu() is called rarely, such as when modules are enabled. If you edit a module’s hook_menu(), you must visit admin/build/modules for the changes to take effect.

The function that invokes the implementations of hook_menu() and hook_menu_alter() is menu_router_build(), which contains the following code (in Drupal 7).

$callbacks = array();
foreach (module_implements('menu') as $module) {
  $router_items = call_user_func($module . '_menu');
  if (isset($router_items) && is_array($router_items)) {
    foreach (array_keys($router_items) as $path) {
      $router_items[$path]['module'] = $module;
    }
    $callbacks = array_merge($callbacks, $router_items);
  }
}
drupal_alter('menu', $callbacks);
list($menu, $masks) = _menu_router_build($callbacks);
_menu_router_cache($menu);

return array($menu, $masks);

The function is called by menu_rebuild(), which is then called by:

drupal_flush_all_caches() is invoked by system_modules_submit(), which is the submission handler for the module page where modules are enabled, and disabled; every time a module is enable, or disabled, the menu is rebuilt, and both the menu hooks are invoked.

0
3

In short: It does.

A print will most like not be visible, because of the timing of the function call. If you use drupal_set_message, you should see a message displayed.

The reason is that the menu is rebuilt as part of the action on the form submit which happens before the page is actually rendered. drupal_set_message is instead stored in the users session, so it will persist a page refresh, much like error messages on form validation.

Also hook_menu_alter should not return anything, instead you change the referenced variable. This is how all drupal's *_alter hooks work.

1

in *_alter hooks the argument is passed by reference (in this case $items), so rather than returning anything just print directly from the alter function.

echo"<pre>";
print_r($items);

and clear cache.

You will able to see the whole array.

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.