Pass array with data to ChoiceType (html select) in Symfony v4.2 Pass array with data to ChoiceType (html select) in Symfony v4.2 symfony symfony

Pass array with data to ChoiceType (html select) in Symfony v4.2


According to the docs, the choices value must be a simple key => value array.

The choices option is an array, where the array key is the item's label and the array value is the item's value

You can easily get the choices array you want using this code:

$choices = [];foreach ($this->userChoices as $choice) {  $choices[$choice['email']] = $choice['id'];}

Then use the following initialization code:

->add('selectUser', ChoiceType::class,    [        'choices' => $choices,        'mapped' => false,        'expanded' => false,        'multiple' => false    ])

Not that I removed choice_value and choice_label which don't serve any purpose in this case.


Simply pass it as a one dimensional array, with emails as keys, and ids as values.

$choices = [    '1st@example.com' => 7,    '2nd@example.com' => 8,];