Dan Chaltiel
Dan Chaltiel

Reputation: 8484

Symfony form ChoiceType with only values

The Symfony documentation says that you should use the use ChoiceType like this :

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

$builder->add('isAttending', ChoiceType::class, array(
    'choices'  => array(
        'Maybe' => null,
        'Yes' => true,
        'No' => false,
    ),
));

However, since my values are simple enough to act like keys, I would like to do something like this :

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

$builder->add('titre', ChoiceType::class, array(
    'choice_value'  => array(
        'Pr', 'Dr', 'Mr', 'Mrs'
    ),
))

How can I achieve this ?

If I cannot, what is the good reason behind ?

Upvotes: 0

Views: 1217

Answers (2)

yceruto
yceruto

Reputation: 9575

A Symfony-ish way:

$builder->add('isAttending', ChoiceType::class, array(
    'choices' => array('Pr', 'Dr', 'Mr', 'Mrs'),
    'choice_label' => function ($value) { return $value; },
));

Upvotes: 1

rokas
rokas

Reputation: 1581

You can try create same key/value array with array_combine:

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

$choices = array('Pr', 'Dr', 'Mr', 'Mrs');

$builder->add('isAttending', ChoiceType::class, array(
    'choices'  => array_combine($choices, $choices),
));

Upvotes: 1

Related Questions