yii2: Show label instead of value for boolean chec

2019-02-12 17:29发布

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.

标签: php yii2
3条回答
等我变得足够好
2楼-- · 2019-02-12 17:54

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',
],
查看更多
再贱就再见
3楼-- · 2019-02-12 18:01

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';
    },
],
查看更多
霸刀☆藐视天下
4楼-- · 2019-02-12 18:16

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',
查看更多
登录 后发表回答