Mauro
Mauro

Reputation: 1487

Symfony2 Option values on ChoiceList

I'm trying to set custom values for Select Options using Form types and 'choice_list'.

Type:

   ->add('status', 'choice', array(
      'constraints' => array(
       new Assert\NotBlank(array('message' => 'Required field missing: status'))
      ),
      'error_bubbling' => true,
      'choice_list' => new StatusChoiceList()

StatusChoiceList file:

class StatusChoiceList extends LazyChoiceList
{
    /**
     * Loads the choice list
     *
     * Should be implemented by child classes.
     *
     * @return ChoiceListInterface The loaded choice list
     */
    protected function loadChoiceList()
    {
        $array = array(
            'Preview' => 'Preview',
            'Hidden'  => 'Hidden',
            'Live'    => 'Live'
        );
        $choices = new ChoiceList($array, $array);

        return $choices;
    }
}

the select tag have a wrong values 0,1,2 and a good labels

Upvotes: 1

Views: 4095

Answers (1)

ozahorulia
ozahorulia

Reputation: 10094

ChoiceList class used for choices of arbitrary data types. In your case you should use SimpleChoiceList instead. First parameter is an array with choices as keys and labels as values.

protected function loadChoiceList()
{
    $array = array(
        'Preview' => 'Preview',
        'Hidden'  => 'Hidden',
        'Live'    => 'Live'
    );
    $choices = new SimpleChoiceList($array);

    return $choices;
}

Upvotes: 3

Related Questions