在使用带有规则类的yii2 RBAC时,如何控制yii2 GridView的ActionColumn中按钮的可见性?

esaepe 发布于 2019-11-08 yii2 最后更新 2019-11-08 22:59 20 浏览

我明白ActionColumn按钮的可见性可以像这样控制:

<?= 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')
            ]
],
        ],
    ]);
?>
我创建了基于yii2文档
的RBAC授权和AuthorRule Rule类 http://www.yiiframework.com/doc-2.0/guide-security-authorization.html 在roleParams的情况下,我已经实现了如下所示(在视图模板中):
if (\Yii::$app->user->can('updatePost', ['post' =>$model]){
//if the post is created by current user then do this
}
如何弄清楚GridView小部件中的模型或至少id,以便我可以执行如下操作:
    '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)])
    ]
我的最终目标是,对于具有作者角色的用户,只有当该帖子由该用户创建时,才能看到更新和删除按钮。任何其他想法也是可以实现的。 谢谢 !
已邀请:

fdolor

赞同来自:

你可以用visibleButtons做同样的事情:

'visibleButtons' => [
    'update' => function ($model) {
        return \Yii::$app->user->can('updatePost', ['post' => $model];
    },
    'delete' => function ($model) {
        return \Yii::$app->user->can('updatePost', ['post' => $model];
    },
]