How to make that GridView buttons update and delet

2019-07-27 04:03发布

问题:

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);

} 

                },

            ],

        ],


标签: yii2