I have created a check-box input as type Boolean for storing values as dishcharged - checked or unchecked. Checked will store 1 and unchecked will store 0.
Now I want to show the label as Yes or No for value 1 and 0 in grid-view and view. How can achieve that.
my _form.php code is like
$form->field($model, 'discharged')->checkBox(['label' => 'Discharged',
'uncheck' => '0', 'checked' => '1'])
I have tried like
[
'attribute'=>'discharged',
'value'=> ['checked'=>'Yes','unchecked=>'no']
],
but doesn't look like the correct syntax.
Thanks.
First option:
[
'attribute' => 'discharged',
'format' => 'boolean',
],
or shortcut:
'discharged:boolean',
This does not require additional methods in your model and writing text labels (it will be set automatically depending on language in your config).
See more details here.
Second option:
Instead of writing additional method in model you can just pass closure to value
.
You can check details here.
[
'attribute' => 'discharged',
'value' => function ($model) {
return $model->discharged ? 'Yes' : 'No';
},
],
As arogachev said, you should use 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
Or you could add a getDischargedLabel()
function in your model :
public function getDischargedLabel()
{
return $this->discharged ? 'Yes' : 'No';
}
And in your gridview :
[
'attribute'=>'discharged',
'value'=> 'dischargedLabel',
],
If you consistently display booleans the same way in your app, you can also define a global boolean formatter:
$config = [
'formatter' => [
'class' => 'yii\i18n\Formatter',
'booleanFormat' => ['<span class="glyphicon glyphicon-remove"></span> no', '<span class="glyphicon glyphicon-ok"></span> Yes'],
],
];
Then add your column:
'discharged:boolean',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With