2012-12-03 37 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 
    )); 
    } 
}