Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony ChoiceType populate choices dynamically and initialize empty choices array

Tags:

php

symfony

I'm trying to define some ChoiceType in Symfony 3.0.9 in forms where there are populated with ajax depending on how many options are created dynamical, but then the validation form says that the option selected is not valid.

I define the ChoiceType like this:

->add('position', ChoiceType::class, [
    'placeholder' => 'Select position',
    'choices'  => [],
    'attr' => [
       'class' => 'form-control choice-position'
    ],
 ])

And the error I get is:

Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).children[lessonGroups].children[0].children[position] = 1

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Unable to reverse value for property path "position": The choice "1" does not exist or is not unique

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
The choice "1" does not exist or is not unique

I don't know if there's needed any further information.

Thank you!

like image 513
Jose M Avatar asked Jan 16 '26 21:01

Jose M


1 Answers

Because your definition does not include any choices ('choices' => [],) Symfony detect than a user try to submit a result not in the initial authorized results.

You could set an initial array of choices containing all the values available or you could disable that validation by using:

$builder->get('yourField')->resetViewTransformers();
like image 151
goto Avatar answered Jan 19 '26 12:01

goto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!