Drupal 7: Add Item to Admin Toolbar/Menu Programmatically
Asked Answered
K

1

5

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.

Kurtis answered 19/5, 2014 at 19:25 Comment(0)
R
12

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.

Roberto answered 20/5, 2014 at 6:17 Comment(1)
This worked well. As a note, I didn't need the system_admin_menu_block_page. I was able to set 'page callback' to anything. I think it was the position, weight, file, and file path arguments that did it.Kurtis

© 2022 - 2024 — McMap. All rights reserved.