Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control visibility of buttons in ActionColumn of yii2 GridView when using yii2 RBAC with a rule class?

I understand the visibility of ActionColumn buttons can be controlled like this :

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'title',
            'body:ntext',

            // ['class' => 'yii\grid\ActionColumn'],
            [
            'class' => 'yii\grid\ActionColumn',
            'visibleButtons' =>
            [
                'update' => Yii::$app->user->can('updatePost'),
                'delete' => Yii::$app->user->can('updatePost')
            ]

          ],
        ],
    ]);
?>

I have created RBAC authorisation, and a AuthorRule Rule class based on yii2 docs
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

In case of roleParams I have achieved this like below (in view template):

if (\Yii::$app->user->can('updatePost', ['post' =>$model]){
//if the post is created by current user then do this
}

How to figure out the model or atleast id in GridView widget in order for me to do something like :

    'visibleButtons' =>
    [
        'update' => Yii::$app->user->can('updatePost',['post' => \app\models\Post::findOne($howToGetThisId)]),
        'delete' => Yii::$app->user->can('updatePost',['post' => \app\models\Post::findOne($howToGetThisId)])
    ]

My end goal here is that for a user with author role, update and delete buttons are visible only if the post was created by that user. Any other ideas are also welcome to achieve this.

Thank you !

like image 336
Ajinkya Devasthali Avatar asked Nov 24 '17 10:11

Ajinkya Devasthali


1 Answers

You can do the same with visibleButtons :

'visibleButtons' => [
    'update' => function ($model) {
        return \Yii::$app->user->can('updatePost', ['post' => $model]);
    },
    'delete' => function ($model) {
        return \Yii::$app->user->can('updatePost', ['post' => $model]);
    },
]
like image 51
Insane Skull Avatar answered Oct 09 '22 21:10

Insane Skull