Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7: Add Item to Admin Toolbar/Menu Programmatically

I'm building a fairly involved module for my company with a number of different configuration pages. I'd like there to be a menu item in the admin bar across the top that has all the sub menu items as well. I know how to add a single item to that menu through the UI, but there will be enough pages I'd just prefer to do it through the module itself. So, how can I add an item with a submenu to sit up alongside 'Dashboard', 'Content', 'Structure', etc. in the admin menu in my module file. I assumed it had to be in hook_menu(), but I can't figure it out.

like image 848
LoneWolfPR Avatar asked May 19 '14 19:05

LoneWolfPR


1 Answers

This could be achieved by adding a 'page callback' of system_admin_menu_block_page to your hook_menu implementation:
So, lets say you want to create a structure like the following :

  • Custom main menu (will appear on the toolbar, besides other items like Structure, Modules, etc)
    • Sub menu item 1
    • Sub menu item 2

The hook implementation would be something like :

function MODULE_menu() {
  $items['admin/main'] = array(
    'title' => 'Custom main menu',
    'description' => 'Main menu item which should appear on the toolbar',
    'position' => 'left',
    'weight' => -100, // Less weight so that it will appear to the extreme left, before dashboard.
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer site configuration'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );

  $items['admin/main/sub-menu-1'] = array(
    'title' => 'Sub menu item 1',
    'description' => 'Child of the menu appearing in toolbar.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_form'),
    'access arguments' => array('custom permission'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/main/sub-menu-2'] = array(
    'title' => 'Sub menu item 2',
    'description' => 'Child of the menu appearing in toolbar.',
    'page callback' => 'custom_page_callback',
    'access arguments' => array('custom permission'),
    'type' => MENU_NORMAL_ITEM,
  );
}

P.S - After enabling the module, or adding this code to the hook_menu implementation, you'll have to flush the cache so that Drupal picks up the new menu structure.

like image 128
Ajit S Avatar answered Sep 30 '22 02:09

Ajit S