16

Is it possible to disable backend (server-side) validation for the specified field?

Wnen Im trying to send form with dynamicly loaded options I get error "ERROR: This value is not valid."

I think symfony is checking if my value is on the default declared list (in my case its empty list), if not returns false.

hywak
  • 890
  • 1
  • 14
  • 27

3 Answers3

40

It's confusing but this behaviour is not really validation related as it is caused by the "ChoiceToValueTransformer" which indeed searches for entries in your pre-declared list. If your list is empty or you want to disable the transformer you can simply reset it.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('yourField', 'choice', array('required'=>false));

    //more fields...

    $builder->get('yourField')->resetViewTransformers();
}

Then your custom defined validation will step in (if it exists).

Atan
  • 1,095
  • 2
  • 12
  • 17
  • 1
    Your solution had no effect for me in symfony 2.8. But this helped: http://stackoverflow.com/questions/12946461/validating-dynamically-loaded-choices-in-symfony-2 – fabpico Feb 08 '16 at 15:07
  • 1
    If I use the resetViewTransformers option it works, only when the form is reloaded because an other field gave an error the choice value is lost. Do you have an idee how to fix this? – Tom Jul 27 '16 at 21:51
  • This saved me so badly in symfony 4.2 after couple of hours of search. Works perfectly. In my case I render fields in twig in the `form type template`, which is not equal to what i pass in. I could not force `isValid()`, and kept getting `invalid value`. – Volmarg Reiso Aug 26 '19 at 15:49
1

Add this inside buildForm method in your form type class so that you can validate an input field value rather a choice from a select field value;

$builder->addEventListener(
    FormEvents::PRE_SUBMIT,

    function (FormEvent $event) {
        $form = $event->getForm();

        if ($form->has('field')) {
            $form->remove('field');
            $form->add(
                'field', 
                'text', 
                ['required' => false]
            )
        }
    }
);
ssrp
  • 1,126
  • 5
  • 17
  • 35