2

My Symfony model has a field which is boolean but also accepts NULL so effectively is a tri-state value.

How can I write a widget for this? Symfony auto-generates a sfWidgetFormCheckbox but that can not be set to NULL.

I tried a sfWidgetFormChoice with but I had to specify the values as strings to get them work:

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

It works for storing values but whenever I save a "false" value, the select jumps back to 'null'. I tried several combinations of 'false', '0', '' etc. but got nothing to work in all three cases.

Any ideas?

1
  • 1
    Have you tried 'null' => 'null' and creating a custom validator that looks for the string null and returns the proper value? Commented Dec 3, 2012 at 15:07

1 Answer 1

5

An example right from the 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
    ));
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.