2012-12-03 41 views
1

我的Symfony模型有一個布爾型的字段,但也接受NULL,所以有效的是三態值。創建一個接受空值的布爾表單構件

如何爲此編寫小部件? Symfony自動生成一個sfWidgetFormCheckbox,但 不能設置爲NULL。

我試着用sfWidgetFormChoice,但我不得不指定的值作爲字符串,讓他們的工作:

$this->setWidget('wt', new sfWidgetFormChoice(array(
    'choices' => array(true => 'true', false => 'false', null => 'null') 
))); 

它可以用於存儲值,但每當我救一個「假」值,選擇跳回'空值'。我嘗試了'假','0',''等幾種組合,但在三種情況下都沒有任何工作。

任何想法?

+1

您是否嘗試過'「空」 =>「null''並創建一個自定義驗證,以查找字符串'null'並返回正確的價值? – jaudette

回答

3

一個例子,從一docs

class sfWidgetFormTrilean extends sfWidgetForm 
{ 
    public function configure($options = array(), $attributes = array()) 
    { 

    $this->addOption('choices', array(
     0 => 'No', 
     1 => 'Yes', 
     'null' => 'Null' 
    )); 
    } 

    public function render($name, $value = null, $attributes = array(), $errors = array()) 
    { 
    $value = $value === null ? 'null' : $value; 

    $options = array(); 
    foreach ($this->getOption('choices') as $key => $option) 
    { 
     $attributes = array('value' => self::escapeOnce($key)); 
     if ($key == $value) 
     { 
     $attributes['selected'] = 'selected'; 
     } 

     $options[] = $this->renderContentTag(
     'option', 
     self::escapeOnce($option), 
     $attributes 
    ); 
    } 

    return $this->renderContentTag(
     'select', 
     "\n".implode("\n", $options)."\n", 
     array_merge(array('name' => $name), $attributes 
    )); 
    } 
}