【问题标题】:yii2: Show label instead of value for boolean checkboxyii2:显示标签而不是布尔复选框的值
【发布时间】:2015-02-05 21:50:06
【问题描述】:

我创建了一个作为布尔类型的复选框输入,用于将值存储为空心 - 选中或未选中。选中将存储 1,未选中将存储 0。

现在我想在网格视图和视图中将值 1 和 0 的标签显示为 YesNo。如何做到这一点。

我的 _form.php 代码是这样的

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

我试过了

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

但看起来不像正确的语法。

谢谢。

【问题讨论】:

    标签: php yii2


    【解决方案1】:

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

    在您的网格视图中:

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

    【讨论】:

    • 完美运行。非常感谢。
    【解决方案2】:

    第一个选项:

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

    或快捷方式:

    'discharged:boolean',
    

    这不需要您的模型中的其他方法和编写文本标签(它将根据您的配置中的语言自动设置)。

    查看更多详情here

    第二个选项:

    您可以将闭包传递给value,而不是在模型中编写其他方法。 您可以查看详情here

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

    【讨论】:

    • @arogachev 这要简单得多
    • 是的,你只需要'discharged:boolean'作为列定义
    • 是的,忘了提到可用的快捷方式。
    • Pawan : 你可以接受这个答案而不是我的 :-)
    • 应该是 $model->discharged 而不是 $this->discharged 。
    【解决方案3】:

    如果您在应用中始终以相同的方式显示布尔值,您还可以定义一个全局布尔格式化程序:

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

    然后添加您的列:

    'discharged:boolean',
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2017-08-11
      • 2014-08-20
      • 2012-01-07
      • 2017-09-24
      相关资源
      最近更新 更多