Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 form validation based on two fields

Tags:

I am currently developing a Website in which user may buy gift cards. I am using a three step form using the CraueFormFlow bundle and everything is concerning the steps. I am able to validate every simple Assert (like not blank, email, repeated fields, etc) but I am facing the situation where, user may select 0 gift cards and proceed to the next page.

The users may choose the quantity of giftcards they want to buy using two separate : one for 25$ gift cards and one for 50$ gift cards. So I can't just put a validator saying "value 0 is not allowed". The validator must prevent a user from leaving the quantity "0" in both amount (25$ and 50$).

Does anyone know how to make a custom validation looking for the values in two fields?

Thanks in advance!

like image 548
Jean-Francois Hamelin Avatar asked Nov 17 '11 16:11

Jean-Francois Hamelin


1 Answers

You have many solutions for this.

The easiest one is to add a Callback constraint to your model class.

Another way to do it would be to create your custom constraint and its associated validator. You have a cookbook explaining how to create a custom validation constrain. This is the best approach to do it.

As your constraint does not apply to a property but to a class, you must specify it overriding the the ->getTargets() method of your constraint class:

class MyConstraint extends Constraint {     // ...      public function getTargets()     {         return Constraint::CLASS_CONSTRAINT;     } } 

So the value passed as $value argument of the ->isValid() method will contain values of the whole class and not only of a single property.

like image 67
Herzult Avatar answered Nov 30 '22 05:11

Herzult