2014-12-08 99 views
7

我創建了一個複選框輸入作爲布爾類型,用於存儲值爲dishcharged - 選中或未選中。經過將存儲1和未選中將存儲0yii2:顯示標籤而不是布爾值複選框的值

現在我要顯示在網格視圖和查看標籤爲沒有爲值1和0。如何才能做到這一點。

我_form.php這個代碼是這樣

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

我試圖像

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

,但並不像正確的語法。

謝謝。

回答

10

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

而且在你的gridview:

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

運行完美。非常感謝你。 – Pawan 2014-12-08 09:46:43

6

第一種選擇:

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

或快捷方式:

'discharged:boolean', 

這並不需要在模型中的其他方法和寫作文本標籤(它會自動設置爲根據語言在你的配置)。

查看更多詳情here

第二個選項:

而是在模型編寫額外的方法,你可以只通過關閉到value。 你可以查看詳細信息here

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

忘了布爾格式化程序,+1 – soju 2014-12-08 10:11:47

+0

@arogachev這簡單得多 – Pawan 2014-12-08 10:12:51

+0

是的,你只需要'放棄:布爾'作爲列定義 – soju 2014-12-08 10:13:26

2

如果你一貫展示布爾在您的應用程序以同樣的方式,你也可以定義一個全局布爾格式:

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

添加您的列:

'discharged:boolean',