2

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!

2

2 Answers 2

9

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();
Sign up to request clarification or add additional context in comments.

2 Comments

¡Oh! I didn't know that. I suposed that if I fill after that array the definition will not care... Anyway I just added that code line and worked perfect. Thank you!
To avoiod disabling the validation - you could put in the options/choices dynamically - I feel that it's important to note there are 2 important things available - 1) $builder->getData() to get currently loaded data into form and 2) RequestStack which can help you get data from request if needed like $this->requestStack->getCurrentRequest()?->request?->all()['some_form']['some_field'] ?? someDefaultValue;
0

In case your are using an eveListener where you cannot have access to the builder, I transform the Type to a textType for PRE_SUBMIT Event. thus it does not got thrue the ChoiceType validation process.

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
        dump($data);
        if($data !== null && strlen($data['value'])!==0){
            $form->add('value','Symfony\Component\Form\Extension\Core\Type\TextType',[]);
        }
    }); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.