Yii - 如何在CGridview中隐藏/查看基于用户级别的按钮?

时间:2014-03-25 04:23:04

标签: php yii

我试图在我的/views/file/admin.php中查看或显示CGridView中的按钮(CButtonColumn):

....
//getLevel()==1 means ADMIN, getLevel==2 means common users
array(
        'class'=>'bootstrap.widgets.TbButtonColumn',
            'template'=>'{view}{update}{delete}', 'visible'=> (Yii::app()->user->getLevel()==1),
            'deleteConfirmation'=>"js: 'Are you want to delete '+$(this).parent().parent().children(':first-child').text()+ '?'",

  //I tried to modify with this code below, but there's nothing happens, 'view' button not
  //display when I access as common user (getLevel()==2)    
            'buttons'=>array(
                'view' => array(
                    'visible'=> Yii::app()->user->getLevel()==2,
                ),

            )
    ),
....

WebUser.php

<?php
class WebUser extends CWebUser{

protected $_model;

protected function loadUser()
{
    if ( $this->_model === null ) {
            $this->_model = User::model()->findByPk($this->id);
    }
    return $this->_model;
}

function getLevel()
{
    $user=$this->loadUser();
    if($user)
        return $user->id_level;
    return 100;
}
}
?>

我试着去做那个代码,但是那里有&#39; view&#39;按钮不显示,加载页面时没有错误。任何人都可以帮我解决这个问题吗?非常感谢。

2 个答案:

答案 0 :(得分:2)

您已经在行

上将列可见性设置为管理员用户
'template'=>'{view}{update}{delete}', 'visible'=> (Yii::app()->user->getLevel()==1),

所以

    'view' => array(
        'visible'=> Yii::app()->user->getLevel()==2,
    ),

无效。删除visible的第一个设置。同样@soju和@Rafay说visible应该是一个php表达式因此它应该读取

    'view' => array(
        'visible'=> 'Yii::app()->user->getLevel()==2',
    ),

答案 1 :(得分:0)

在您的情况下,您需要扩展bootstrap.widgets.TbButtonColumn

Yii::import('zii.widgets.grid.CButtonColumn');

class EButtonColumnWithRightsCheck extends CButtonColumn{

    public function init() {
        //{view} {delete} {update}
        $permissions = array();
        // Client.User.View
        $permissions['view'] = Yii::app()->user->checkAccess(ucfirst($this->grid->controller->module->id) . '.' . ucfirst($this->grid->controller->id) . '.View');
        $permissions['delete'] = Yii::app()->user->checkAccess(ucfirst($this->grid->controller->module->id) . '.' . ucfirst($this->grid->controller->id) . '.Delete');
        $permissions['update'] = Yii::app()->user->checkAccess(ucfirst($this->grid->controller->module->id) . '.' . ucfirst($this->grid->controller->id) . '.Update');

        foreach ($permissions as $action => $permission) {
            if ($permission === false) {
                $this->template = str_replace('{' . $action . '}', '', $this->template);
            }
        }

        // call parent to initialize other buttons
        parent::init();
    }

}