用于添加标签的drupal hook_menu_alter()

Eri*_*icP 3 hook tabs drupal menu alter

我想在名为"cssswitch"的模块的"node /%/ edit"页面中添加一些选项卡.当我单击"Rebuild Menus"时,会显示两个新选项卡,但在编辑它们时会显示所有节点,而不仅仅是节点"cssswitch".我希望仅在编辑"cssswitch"类型的节点时才显示这些新选项卡.

另一个问题是当我清除所有缓存时,选项卡完全消失在所有编辑页面中.以下是我写的代码.

    function cssswitch_menu_alter(&$items) {

        $node = menu_get_object();
        //print_r($node);
        //echo $node->type; //exit();
        if ($node->type == 'cssswitch') {

            $items['node/%/edit/schedulenew'] = array(
                'title' => 'Schedule1',
                'access callback'=>'user_access',
                'access arguments'=>array('view cssswitch'),
                'page callback' => 'cssswitch_schedule',
                'page arguments' => array(1),
                'type' => MENU_LOCAL_TASK,
                'weight'=>4,
            );

            $items['node/%/edit/schedulenew2'] = array(
                'title' => 'Schedule2',
                'access callback'=>'user_access',
                'access arguments'=>array('view cssswitch'),
                'page callback' => 'cssswitch_test2',
                'page arguments' => array(1),
                'type' => MENU_LOCAL_TASK,
                'weight'=>3,
            );  


        }

    }

function cssswitch_test(){
    return 'test';
}

function cssswitch_test2(){
    return 'test2';
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

jhe*_*rom 8

hook_menu_alter()仅在菜单构建过程中调用,因此您无法在该函数中执行动态节点类型检查.

但是,要实现您想要的功能,您可以使用自定义访问回调执行此操作,如下所示:

       // Note, I replaced the '%' in your original code with '%node'. See hook_menu() for details on this.
       $items['node/%node/edit/schedulenew2'] = array(
            ...
            'access callback'=>'cssswitch_schedulenew_access',
            // This passes in the $node object as the argument.
            'access arguments'=>array(1),
            ...
        );  
Run Code Online (Sandbox Code Playgroud)

然后,在您的新自定义访问回调中:

function cssswitch_schedulenew_access($node) {
  // Check that node is the proper type, and that the user has the proper permission.
  return $node->type == 'cssswitch' && user_access('view cssswitch');
}
Run Code Online (Sandbox Code Playgroud)

对于其他节点类型,此函数将返回false,从而拒绝访问,从而删除选项卡.

  • +1 - 只需一个注释:`hook_menu_alter()`应该用于改变其他模块提供的菜单项.由于OP想要添加新条目,他应该只使用`hook_menu()`. (6认同)