簡體   English   中英

Yii - 如何根據用戶級別隱藏/查看CGridview中的按鈕?

[英]Yii - How to Hide/View Button in CGridview Based on User's Level?

我試圖在我的/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;
}
}
?>

我嘗試執行該代碼,但是“視圖”按鈕不顯示,並且在加載頁面時沒有錯誤。 任何人都可以幫我解決這個問題嗎? 非常感謝。

您已經將列可見性設置為僅在該行上的管理員用戶

'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',
    ),

在您的情況下,您需要擴展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();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM