【问题标题】:Creating a boolean form widget that accepts null value创建一个接受空值的布尔表单小部件
【发布时间】:2012-12-03 14:45:05
【问题描述】:

我的 Symfony 模型有一个布尔字段,但也接受 NULL,因此有效地是一个三态值。

如何为此编写小部件? Symfony 自动生成一个 sfWidgetFormCheckbox 但是 不能设置为NULL。

我尝试了 sfWidgetFormChoice,但我必须将值指定为字符串才能使它们工作:

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

它适用于存储值,但每当我保存“假”值时,选择会跳回“空”。我尝试了 'false'、'0'、'' 等的几种组合,但在所有三种情况下都没有任何效果。

有什么想法吗?

【问题讨论】:

  • 您是否尝试过'null' => 'null' 并创建了一个自定义验证器来查找字符串null 并返回正确的值?

标签: symfony1 widget symfony-1.4 propel symfony-forms


【解决方案1】:

来自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
    ));
  }
}

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 2014-01-06
    • 2016-12-09
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多