Elgg Blog: Elgg's New Menu System: Dynamic menus

By Cash

This is the second post in a series on Elgg's new menu system. Last time I explained how to register a menu item during initialization and just before the menu is rendered. In this post, I explain how to take advantage of the just-in-time registration to create dynamic menus.

Dynamic Menus

A dynamic menu in Elgg is one that varies its links based on an input. A prime example of a dynamic menu is the user hover menu that appears on avatars on mouseover. The links on the user hover menu change based on user. To accomplish this, the ElggUser entity for the user is passed when the menu is rendered:

$params = array(
'entity' => $user,
'username' => $username,
'name' => $name,
echo elgg_view_menu('user_hover', $params);

As explained last time, there is a plugin hook triggered before elgg_view_menu() renders the menu. The name of the hook is 'register', 'menu:<name of the menu>' and it passes any registered menu items plus any parameters passed to the elgg_view_menu() function. Plugins that registered for the hook 'register', 'menu:user_hover' can create a menu item that depends on any of the parameters passed to elgg_view_menu().

Consider the log browser plugin. It adds a menu item to the admin section of the user hover menu:

function logbrowser_user_hover_menu($hook, $type, $return, $params) {
$user = $params['entity'];

$url = "admin/utilities/logbrowser?user_guid={$user->guid}";
$item = new ElggMenuItem('logbrowser', elgg_echo('logbrowser:explore'), $url);
$return[] = $item;
return $return;

When all the handlers for that plugin hook have completed, the menu is divided into sections, sorted, and rendered. The elgg_view_menu() function then returns the rendered HTML for inclusion with a user's avatar.

Other Dynamic Menus

The user hover menu isn't the only dynamic menu provided by Elgg. Another common one is the entity menu. The entity menu is used when listing or viewing content like blog posts or files. It has information about the entity like access level and links for editing or liking the content.

entity menu

There is a list of additional dynamic menus in engine/lib/navigation.php. Of course, developers are not limited to using those menus. If a developer wants to add a new menu (whether dynamic or not), this can be done by calling elgg_view() with a unique identifier for the menu.

What's Next?

In the next post in this series, I will cover optional parameters for menu registration (like sections, tool-tips, and CSS classes).

Latest comments