Drupal 7 tip: Use menu local tasks for on page tasks

Posted by: 
Dominique De Cooman

A handy new feature in drupal 7 are the local tasks. We will quickly explain two ways of adding them. Everybody should be
familiar with the two examples to be found in the node module. First example is the add content type on ''admin/structure/types".

First method to create a local task, we can use a hook_menu()

<?php
/**
 * Implements hook_menu().
 */
function node_menu() {

  
//...

 
$items['admin/structure/types'] = array(
    
'title' => 'Content types',
    
'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
    
'page callback' => 'node_overview_types',
    
'access arguments' => array('administer content types'),
    
'file' => 'content_types.inc',
  );
  
$items['admin/structure/types/list'] = array(
    
'title' => 'List',
    
'type' => MENU_DEFAULT_LOCAL_TASK,
    
'weight' => -10,
  );
  
$items['admin/structure/types/add'] = array(
    
'title' => 'Add content type',
    
'page callback' => 'drupal_get_form',
    
'page arguments' => array('node_type_form'),
    
'access arguments' => array('administer content types'),
    
'type' => MENU_LOCAL_ACTION,
    
'file' => 'content_types.inc',
  );

  
//...
}
?>

In the "admin/structure/types/add" item you can see that a MENU_LOCAL_ACTION is added. When doing this a local task is created on the page.

In the page tpl you ll find which will render out the local tasks.


      <?php if ($action_links): ?>
        <ul class="action-links">
          <?php print render($action_links); ?>
        </ul>
      <?php endif; ?>

In the second example we want to add local task without having to create a menu item, because the menu item we want to use already exists. In the node module we find the "node/add" local task on "admin/content/node". To do something similar: this is done with hook_menu_local_tasks_alter() See here the example from the node module.

<?php
/**
 * Implements hook_menu_local_tasks_alter().
 */
function node_menu_local_tasks_alter(&$data$router_item$root_path) {
  
// Add action link to 'node/add' on 'admin/content' page.
  
if ($root_path == 'admin/content') {
    
$item menu_get_item('node/add');
    if (
$item['access']) {
      
$data['actions']['output'][] = array(
        
'#theme' => 'menu_local_action',
        
'#link' => $item,
      );
    }
  }
}
?>

Note how access is checked using the items access property. This is important so you dont show links to unauthorized users.

Add new comment