2014-12-08 98 views
7

我创建了一个复选框输入作为布尔类型,用于存储值为dishcharged - 选中或未选中。经过将存储1和未选中将存储0yii2:显示标签而不是布尔值复选框的值

现在我要显示在网格视图和查看标签为没有为值1和0。如何才能做到这一点。

我_form.php这个代码是这样

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

我试图像

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

,但并不像正确的语法。

谢谢。

回答

10

正如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'; 
} 

而且在你的gridview:

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

运行完美。非常感谢你。 – Pawan 2014-12-08 09:46:43

6

第一种选择:

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

或快捷方式:

'discharged:boolean', 

这并不需要在模型中的其他方法和写作文本标签(它会自动设置为根据语言在你的配置)。

查看更多详情here

第二个选项:

而是在模型编写额外的方法,你可以只通过关闭到value。 你可以查看详细信息here

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

忘了布尔格式化程序,+1 – soju 2014-12-08 10:11:47

+0

@arogachev这简单得多 – Pawan 2014-12-08 10:12:51

+0

是的,你只需要'放弃:布尔'作为列定义 – soju 2014-12-08 10:13:26

2

如果你一贯展示布尔在您的应用程序以同样的方式,你也可以定义一个全局布尔格式:

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

添加您的列:

'discharged:boolean',