yii2:显示标签而不是布尔复选框的值

时间:2014-12-08 09:08:24

标签: php yii2

我创建了一个复选框输入作为类型布尔值,用于将值存储为dishcharged - 已选中或未选中。 Checked将存储1并且未选中将存储0。

现在,我想在网格视图和视图中将值1和0显示为。怎么能实现这一点。

我的_form.php代码就像

$form->field($model, 'discharged')->checkBox(['label' => 'Discharged', 
'uncheck' => '0', 'checked' => '1'])

我试过像

[
'attribute'=>'discharged',
'value'=> ['checked'=>'Yes','unchecked=>'no']
],

但看起来不正确的语法。

感谢。

3 个答案:

答案 0 :(得分:11)

正如arogachev所说,你应该使用boolean formatter:

'discharged:boolean',

http://www.yiiframework.com/doc-2.0/guide-output-formatter.html

http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html#asBoolean()-detail

或者您可以在模型中添加getDischargedLabel()功能:

public function getDischargedLabel()
{
    return $this->discharged ? 'Yes' : 'No';
}

在你的gridview中:

[
    'attribute'=>'discharged',
    'value'=> 'dischargedLabel',
],

答案 1 :(得分:8)

第一个选项:

[
    'attribute' => 'discharged',
    'format' => 'boolean',
],

或捷径:

'discharged:boolean',

这不需要模型中的其他方法和编写文本标签(它将根据配置中的语言自动设置)。

查看更多详情here

第二个选项:

您可以将闭包传递给value,而不是在模型中编写其他方法。 您可以查看详细信息here

[
    'attribute' => 'discharged',
    'value' => function ($model) {
        return $model->discharged ? 'Yes' : 'No';
    },
],

答案 2 :(得分:3)

如果您在应用中始终以相同的方式显示布尔值,您还可以定义全局布尔格式化程序:

$config = [
        'formatter' => [
          'class' => 'yii\i18n\Formatter',
          'booleanFormat' => ['<span class="glyphicon glyphicon-remove"></span> no', '<span class="glyphicon glyphicon-ok"></span> Yes'],
        ],
    ];

然后添加你的专栏:

'discharged:boolean',
相关问题