How Menu Works In Drupal
In this article I will teach you how menu works in Drupal and how you can use it & modify it.
Menu system defines navigation menus and transforms page requests to calls of functions which are connected with site paths.
Drupal menu system manage as navigation system in the eye of a user as well callback system used by Drupal to respond URL received from a browser. Therefore the correct understanding of menu system is a key to creating complex modules.
Drupal menu system supports simple hierarchy defined by paths. Different realizations of hook_menu()
defines menu items and assign paths for them (the paths have to be unique). Menu system collects these items and defines menu hierarchy from paths. For example, if the paths are: a, a/b, e, a/b/c/d, f/g, and a/b/h, then the system will generate the following structure:
- a
- a/b
- a/b/c/d
- a/b/h
- a/b
- e
- f/g
Note: number of components in a path may define depth of a menu item in a tree but doesn’t have to.
When a page is requested, menu system checks if the requested path was registered as menu item with a callback (a function that corresponds to this path). If wasn’t, the system keep searching for the most full match in a tree (with a callback). If a/b/i path was requested in the above tree, callback for a/b will be used.
Callback of the found menu item is called with arguments in order determined in 'page arguments'
of the menu item specification. Arguments have to be located in an array. After these arguments, additional arguments are added to the path components. This way a/b callback in our example can return a/b/i page in other way than it returns a/b/j.
Access to callback functions is also defined by menu system. Access callback with unnecessary access arguments is called before page callback is completed. If it returns TRUE
, access enabled; if FALSE – access is denied. Menu items might sip this argument to use value of a parent item.
In the default Drupal interface, you’ll find lot of links which appear as tabs. Menu system calls them local tasks and their default appearance is tabs (although there is an ability to change the appearance). Local task work the same way like menu items do. There is an agreement that says these tasks should be described in short nouns, as short as possible. In addition, local task have to be included to any set by default. When visiting parent menu item for a local task, the local task will be shown as it is selected. General experience of working with user tabs require this. The task is a unique by default because it shows a path to a parent item (instead of the assigned path). Path of the default task is used just to allocate it in the menu hierarchy.
Everything described is stored in 'menu_router' table
. Visible links are stored in 'menu_links' table
. By default, they are got from the same definitions via hook_menu()
, but you can simply add more via menu_link_save()
.