yuri
yuri

Reputation: 585

How I can validate only some validation groups based on some fields in the form itself in Symfony2

I have a big form organized in some validations groups. For every group in the form there is a corresponding checkbox which tell the server to save group data.

When the user post the form, I need to validate only validation groups whose correspond the checked checkboxes because some of their "sub" fields are required, but only if you activate the group. Otherwise the validator must ignore the required fields.

Actually I do that in my controller. I skip the Symfony's normal validation cycle and manually I validate every field checking for the group activation checkbox.

How I can move this validation logic inside the Form class or in a specific Constraint class used by the entity?


EDIT:

As said below is possibile in symfony 2.1, for now i solved:

$request = $this->get('request');

// myEntity knows the business logic to chose validation groups
$myEntity->collectValidationGroups($request);

$form = $this->createForm(new MyEntityType(), $myEntity);

Upvotes: 4

Views: 3063

Answers (2)

Florian Klein
Florian Klein

Reputation: 8915

There is another possibilty than the one offered by 2.1. You can set the validation_groups attribute on the form using $builder->getData():

// inside buildForm method of a form type:
$builder->setAttribute('validation_groups', $builder->getData()->getValidationGroups());

Upvotes: 0

Mun Mun Das
Mun Mun Das

Reputation: 15002

If you are using Symfony 2.1 then you can set validation group based on submitted data. Check this section.

Upvotes: 2

Related Questions