Yii2 由不同属性值定义的网格视图属性格式



我想根据 db 字段值定义GridView中属性的格式。例如,我尝试这样:

'format' => function ($model) {return $model->format;}, // it should return 'boolean'

但我也尝试了许多其他方法,但它不起作用。我得到:

PHP 通知 – yii\base\ErrorException

尝试获取非对象的属性

如果我只是将format作为属性返回,那么它可以正常工作。似乎在format部分不接受它。 无论如何,我想要实现的目标是否可能?你能指出我正确的方向吗?

不支持formatClosures。您可以使用raw格式并在Closure中格式化value

[
'attribute' => 'name',
'type' => 'raw',
'value' => function ($model) {
$format = 'as' . ucfirst($model->format);
return Yii::$app->formatter->$format($model->name);
},
],

参考 Yii2 格式化程序

例:

<?= GridView::widget([
'id' => 'grid-list',
'dataProvider' => $dataProvider,
[
'attribute' => 'format_date',
// 'format' => 'raw',
'value' => function ($model) {
// Here use Yii::$app->formatter->asDate();
// Ex: return Yii::$app->formatter->asDate($model->format_date);
return Yii::$app->formatter->asDate($model->format_date);
},
],
]) ?>

最新更新