将 yii2 RBAC 与规则类一起使用时,如何控制 yii2 GridView 的 ActionColumn 中按钮的可见性?

Aji*_*ali 5 yii2 yii2-basic-app yii2-rbac

我了解 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')
            ]

          ],
        ],
    ]);
?>
Run Code Online (Sandbox Code Playgroud)

我已经创建了 RBAC 授权,以及一个基于 yii2 文档的 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
}
Run Code Online (Sandbox Code Playgroud)

如何找出 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)])
    ]
Run Code Online (Sandbox Code Playgroud)

我的最终目标是,对于具有作者角色的用户,更新和删除按钮仅在帖子由该用户创建时可见。也欢迎任何其他想法来实现这一目标。

谢谢 !

Ins*_*ull 10

你可以用visibleButtons做同样的事情

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