>我创建了一个复选框输入作为布尔类型,用于将值存储为discharge-选中或未选中。选中将存储 1,未选中将存储 0。
现在,我想在网格视图和视图中将值 1 和 0 的标签显示为"是"或"否"。如何实现这一点。
我的_form.php代码是这样的
$form->field($model, 'discharged')->checkBox(['label' => 'Discharged',
'uncheck' => '0', 'checked' => '1'])
我试过像
[
'attribute'=>'discharged',
'value'=> ['checked'=>'Yes','unchecked=>'no']
],
但看起来语法不正确。
谢谢。
正如 arogachev 所说,你应该使用布尔格式化程序:
'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';
}
在您的网格视图中:
[
'attribute'=>'discharged',
'value'=> 'dischargedLabel',
],
第一个选项:
[
'attribute' => 'discharged',
'format' => 'boolean',
],
或快捷方式:
'discharged:boolean',
这不需要在模型中使用其他方法并编写文本标签(将根据配置中的语言自动设置)。
在此处查看更多详细信息。
第二种选择:
无需在模型中编写其他方法,您只需将闭包传递给value
即可。您可以在此处查看详细信息。
[
'attribute' => 'discharged',
'value' => function ($model) {
return $model->discharged ? 'Yes' : 'No';
},
],
如果在应用中始终以相同的方式显示布尔值,则还可以定义全局布尔格式化程序:
$config = [
'formatter' => [
'class' => 'yii'i18n'Formatter',
'booleanFormat' => ['<span class="glyphicon glyphicon-remove"></span> no', '<span class="glyphicon glyphicon-ok"></span> Yes'],
],
];
然后添加列:
'discharged:boolean',