2

I'd like to add, in a custom module, a hook menu that adds a menu only if

  • the user is logged in
  • the user has the role "immat"

I'm trying to use the hook_menu() hook but it's never called when the page displays the "Navigation" menu. Where should I look / which hook should I use?

Thank you very much!

4

hook_menu is not called on every page load, because that make Drupal really slow. It is only called when the menu is being (re)built, and the resulting menu structure is cached.

In hook_menu, you can tell Drupal how to determine which users have access. Access is not granted by role, but by permission. That way, you can easily grant the same permission to other roles when needed.

You will need to:

  • Define a new permission using hook_permission
  • Add the new permission to the role you want to give access
  • Restrict your menu item to users with that permission by adding 'access arguments' => array('[name of your permission]'), to your menu item

For an example, see the menu_example module at api.drupal.org. More specifically, see how menu_example_permission defines a new permission and how menu_example_menu specifies that permission as access arguments for the $items['menu_example/permissioned/controlled'] item.

2
  • Thank you very much, it will take some time to manage to reach my goal, but your explanation showed me the right way to do it. Thank you again! – Olivier Pons Oct 25 '11 at 13:55
  • You're welcome, and thanks for the feedback. When you're doing this for the first time, it may seem time consuming, but you will get faster. If you want to program for Drupal, understanding the menu system is time well spent. – marcvangend Oct 25 '11 at 14:12
0

It may be done without any programming: simply add the Menu by Role module or the Menu Item Visibility module and you will have the option to select for which roles the menu item is enabled. I've tried both of them and ended up working with the first one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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