PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites

22 Dec 2015

Drupal 7 - Create menu tab programmatically

    This blog describes about how to create menu tab programmatically in drupal 7. We can create menu items using hook_menu().

Create menu tab programmatically

Menu tab creation in Drupal 7:


     Consider below code snippet to create menu tab in drupal 7.

/**
 * Implement hook_menu()
 */
function phponwebsites_menu() {

  $items['test'] = array(
    'title' => t('Create Menu Tab'),
    'page callback' => 'testpage_tab1',
    'access callback' => TRUE,
  );

  $items['test/tab1'] = array(
    'title' => t('First Tab'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'testpage_tab1',
    'access callback' => TRUE,
  );

  $items['test/tab2'] = array(
    'title' => t('Second Tab'),
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'testpage_tab2',
    'access callback' => TRUE,
  );

  $items['test/tab3'] = array(
    'title' => t('Third Tab'),
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'testpage_tab3',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Implement testpage_tab1()
 */
function testpage_tab1() {
  $str = t('Hi this is first tab');
  return $str;
}

/**
 * Implement testpage_tab2()
 */
function testpage_tab2() {
  $str = t('Hi this is second tab');
  return $str;
}

/**
 * Implement testpage_tab3()
 */
function testpage_tab3() {
  $str = t('Hi this is third tab');
  return $str;
}


Where,
   In hook_menu,
      Title – page title
      Type – type of menu item,
       MENU_CALLBACK, MENU_DEFAULT_LOCAL_TASK, MENU_LOCAL_TASK, MENU_LOCAL_ACTION, MENU_NORMAL_ITEM, MENU_SUGGESTED_ITEM are types of
menu item in drupal 7.

MENU_CALLBACK – register path for a menu item
MENU_DEFAULT_LOCAL_TASK – default tab for a menu
MENU_LOCAL_TASK – additional tabs for menu
MENU_LOCAL_ACTION – actions for menu items
MENU_NORMAL_ITEM – add menu item into any menus like main_menu, user_menu
MENU_SUGGESTED_ITEM – module may suggest menu items

Page callback – callback for a menu
Access callback – who can access the page

        Now i’ve hope you should know how to create menu tab programmatically in drupal 7.