yii2: Show label instead of value for boolean checkbox

前端 未结 3 1686
灰色年华
灰色年华 2021-01-04 20:03

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 wan

相关标签:
3条回答
  • 2021-01-04 20:26

    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';
        },
    ],
    
    0 讨论(0)
  • 2021-01-04 20:35

    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',
    ],
    
    0 讨论(0)
  • 2021-01-04 20:47

    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',
    
    0 讨论(0)
提交回复
热议问题