Search code examples
symfonysymfony-forms

Send choice Value instead choice key from Symfony form


I need to send from Symfony form ChoiceType::class

But I don't need choices keys, I need to send choices values.

Is that is possible?

 $form->add('section', ChoiceType::class, array(
                'mapped' => false,
                'choices' => array(
                    1 => 'value1',
                    2 => 'value2'

                ),
          ));

I just want to send value1 if I chose value1,

not key 1 as default.


Solution

  • [Since Symfony 2.7] In any case you can play with choice value through choice_value option and a Closure function (Reference):

    $form->add('section', ChoiceType::class, array(
        'choice_value' => function ($value, $key, $index) {
            return $value;
        } 
    ));
    

    Useful for dynamic choices.