Search code examples
phpformssymfony-1.4

Problems with sfValidatorChoice


I have some problems with sfValidatorChoice. This is the array for the choice:

$branches = array(123 => 'Value 1', 456 => 'Value 2', 789 => 'Value 3')

where the numbers are given IDs. To have a default value I do this:

$choices_branches = array_merge(array('default' => 'Bitte wählen'), $branches);

In the form class I do this:

$this->setWidgets(array(
    'branches'    => new sfWidgetFormChoice(array(
                        'choices'  => $choices_branches,
                        'expanded' => false,
                        )),
...))

and this is the validator:

$this->setValidators(array(
  'branches'    => new sfValidatorChoice(array('choices' => array_keys($branches))),
  ...
))

But when I choose for example Value 1 and try to submit the form I get an Invalid Error.

Could anybody help?


Solution

  • From php.net

    Don't forget that numeric keys will be renumbered!

    You should do the following:

    $choices =  array(123 => 'Value 1', 456 => 'Value 2', 789 => 'Value 3');
    $this->setWidget('branches', new sfWidgetFormChoice(array(
        'choices'  => array('' => 'Bitte wählen') + $choices,
        'expanded' => false,
    ));
    $this->setValidator('branches', new sfValidatorChoice(array(
        'choices' => array_keys($choices),
    ));