Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2: Show label instead of value for boolean checkbox

Tags:

php

yii2

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.

like image 527
Pawan Avatar asked Dec 08 '14 09:12

Pawan


3 Answers

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';
    },
],
like image 194
arogachev Avatar answered Oct 21 '22 04:10

arogachev


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',
],
like image 12
soju Avatar answered Oct 21 '22 06:10

soju


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',
like image 3
Christian Lescuyer Avatar answered Oct 21 '22 05:10

Christian Lescuyer