Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: How to add form constraint for a field in bind PRE_SET_DATA depending on the data

I have a form in Symfony 2 with basically two fields:

public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('contactType', 'select', array(  'choices' => $contactTypes ))
            ->add('value', 'text');
}

Then I added an EventSubscriber that listens to the FormEvents::PRE_SET_DATA event. What I actually want to do, is to change the way of validation depending on the value of contactType (numeric values from 1 to 4, which stand for email, mobile, fixed line and fax).

I followed this tutorial http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html

but I can't figure out, how to add a constraint to the value field.

Can anyone help me? Thanks a lot in advance.

like image 387
schingeldi Avatar asked Nov 28 '12 19:11

schingeldi


1 Answers

Instead of adding validation constraints dynamically in event subscriber (not sure if this is even possible), you can set groups to field's validation constraints and determine validation groups based on submitted data.

like image 104
gatisl Avatar answered Nov 15 '22 08:11

gatisl