更改 DetailView 小部件中的属性值

Changing value of an attribute in DetailView widget

我有一个名为 Play 的 table,我在 Yii2 详细视图小部件中显示每条记录的详细信息。我在 table recurring 中有一个属性,它是 tinyint 类型,它可以是 0 或 1。但我不想将其视为数字,而是想显示 yesno 基于值(0 或 1)。

我正在尝试使用详细视图小部件中的函数更改它,但出现错误:Object of class Closure could not be converted to string

我的详情查看代码:

 <?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'name',
        'max_people_count',
        'type',
        [
             'attribute' => 'recurring',
             'format'=>'raw',
             'value'=> function ($model) {
                        if($model->recurring == 1)
                        {

                            return 'yes';

                        } 
                        else {
                        return 'no';
                        }
                      },
        ],
        'day',
        'time',
        ...

如有任何帮助,我们将不胜感激!

尝试

'value' => $model->recurring == 1 ? 'yes' : 'no'

与处理一组模型的 GridView 不同,DetailView 只处理一个模型。所以不需要使用闭包,因为 $model 是唯一一个用于显示的模型,并且可以作为变量在视图中使用。

您当然可以使用 rkm 建议的 ,但还有更简单的选项。

顺便说一句,你可以稍微简化条件,因为允许的值只有 01:

'value' => $model->recurring ? 'yes' : 'no'

如果只想将值显示为布尔值,可以添加带冒号的格式化程序后缀:

'recurring:boolean',

'format' => 'raw' 在这里是多余的,因为它只是没有 html.

的文本

如果你想添加更多选项,你可以使用这个:

[
    'attribute' => 'recurring',
    'format' => 'boolean',    
    // Other options
],

使用格式化程序是更灵活的方法,因为这些标签将根据配置中设置的应用程序语言生成。

官方文档:

另见this question,和你的很像。