hywak
hywak

Reputation: 900

Disable backend validation for choice field in Symfony 2 Type

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.

Upvotes: 16

Views: 19993

Answers (3)

ssrp
ssrp

Reputation: 1266

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]
            )
        }
    }
);

Upvotes: 1

Atan
Atan

Reputation: 1113

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).

Upvotes: 42

Related Questions