blog-banner

Adding Custom Menu Tabs and Menu Items to Navbar

    Mobile-Friendly Navigation Toolbar, shortly known as navbar, is a back-port of the toolbar in Drupal 8. The problem it tries to solve is pretty obvious from its name.

    Navbar is an often used module in our Drupal projects. In our recent project, we were asked to develop a bunch of menus to quickly access admin pages as and when needed. Unlike Shortcuts, we want this to appear dynamically like notification.

    For instance, if there are any new comments awaiting approval, the menu should show up and a few more items similar to this. Thought, Navbar could be leveraged for these requirements.

    This mighty developer-friendly module makes this possible for any module by implementing hook_navbar(). Similar to hook_menu(), an array of menu items is to be returned but in renderable array format. If you need an example, the function navbar_navbar() is a good place to get started.

    The menu it offers can be seen as,

    1. The navbar tab by its name acts as a menu item (e.g. Home)
    2. The navbar tab on click expands to show menu item(s) it has got underneath (e.g. Shortcuts) depending on the way navbar item defined in the hook_navbar().

     

    Example code for #1,

     

    Note: To keep this distinct from other menu tabs you can add custom CSS classes using '#wrapper_attributes'. I have 'pull-right' so I can place it on the right extreme of the toolbar.

    Example code for #2,

     

    Example 2, provides the User name as a menu tab. Once clicked, it shows the profile page link and logout link as menu items.

    Unlike hook_menu(), these items are not cached so we can have dynamic menus.

    I had to write custom CSS to get icons for my custom menu. Below is the CSS I used to place the pencil icon beside the menu tab "unapproved comment".

    .navbar-bar .navbar-icon-comment-unapproved:before {
      background-image: url("../../../contrib/navbar/icons/bebebe/pencil.svg");
    }
    .no-svg .navbar-bar .navbar-icon-comment-unapproved:before {
      background-image: url("../../../contrib/navbar/icons/bebebe/pencil.png");
    }
    .navbar-bar .navbar-icon-comment-unapproved:active:before,
    .navbar-bar .navbar-icon-comment-unapproved.navbar-active:before {
      background-image: url("../../../contrib/navbar/icons/ffffff/pencil.svg");
    }
    .no-svg .navbar-bar .navbar-icon-comment-unapproved:active:before,
    .no-svg .navbar-bar .navbar-icon-comment-unapproved.navbar-active:before {
      background-image: url("../../../contrib/navbar/icons/ffffff/pencil.png");
    }

    I hope this will help. Looking forward to sharing another interesting tip in the next blog.