How to make that GridView buttons update and delete just only visible for admins?

无人久伴 提交于 2019-12-11 06:02:02

问题


I am new to Yii2 and I have 3 kind of user rights:

Admin, moderator and user. I have my GridView and I don't want to show for the user the Update and Delete buttons, just only the GridView. How should I do that?

Here is my actionCreate, there is an input form:

    public function actionCreate()
{
    $model = new Project();
    $model->scenario = Project::SCENARIO_CREATE;

    if ($model->load(Yii::$app->request->post())) {
        if ($model->save()) {
            Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Skelbimas sėkmingai pridėtas!'));
            return $this->redirect(['index']);
        }
    }
    return $this->render('create', [
        'model' => $model,
    ]);
}   

I've tried to search the information according to this, but couldn't find useful ones. Thanks for any help or information.


回答1:


To accomplish this, you have to use the property $visibleButtons of you ActionColum class.

So:

'visibleButtons' = [
    'update' => Yii::$app->user->can('update'), // or whatever condition
    'delete' => Yii::$app->user->can('update')
]

and so on. Each Key on the visibleButtons array is the name of the button.

Yii Framework's guide




回答2:


One possibility would be using the 'template' attribute of youe 'ActionColumn' like:

[
  ...
  'template'=> (user has only user rights ? '{view}' ? '{view} {update} {delete}')
  ...
]

Please, bare in mind that even though this solution will hide the buttons for users with only user right, it won't prevent them of accessing update and delete action urls, so you have to check permissions also in the controller level.




回答3:


        .........
        [
            'class'=>'yii\grid\ActionColumn',

            'template'=> '{view} {update} {delete} ',

            'buttons'=> [
                'update'=> function($url,$model) {
if (Yii::$app->user->can('admin')) {

                    returnHtml::a( '<span class="glyphicon glyphicon-pencil"></span>', $url);

} 

                },

                'delete'=>function($url,$model,$key) {


if (Yii::$app->user->can('admin')) {
                        returnHtml::a('delete', $url);

} 

                },

            ],

        ],


来源:https://stackoverflow.com/questions/43940842/how-to-make-that-gridview-buttons-update-and-delete-just-only-visible-for-admins

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!