5

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 !

1 Answers1

10

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]);
    },
]
ajmedway
  • 1,404
  • 13
  • 26
Insane Skull
  • 8,810
  • 9
  • 38
  • 59