Conditional field check, which depends on another field

I need to change the validation of some field in the form. The validator is configured through a rather large yml file. I wonder if there is a way to do validation on two fields at once. In my case, I have two fields that cannot be empty. At least one must be filled.

Unfortunately, so far I just saw that validation is defined for each field, and not for several fields.

Question: is it possible to perform the above verification in standard yml configurations?

thanks!

+2
source share
1 answer

I suggest you take a look at the Custom Validator , especially Class Conformity Check .

I will not copy all the code, just the parts that you have to change.


Extends the Constraint class.

src / Acme / DemoBundle / Validator / Constraints / CheckTwoFields.php

 <?php namespace Acme\DemoBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; /** * @Annotation */ class CheckTwoFields extends Constraint { public $message = 'You must fill the foo or bar field.'; public function validatedBy() { return 'CheckTwoFieldsValidator'; } public function getTargets() { return self::CLASS_CONSTRAINT; } } 

Define a validator by extending the ConstraintValidator class, foo and bar are the 2 fields you want to check:

src / Acme / DemoBundle / Validator / Constraints / CheckTwoFieldsValidator.php

 namespace Acme\DemoBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; class CheckTwoFieldsValidator extends ConstraintValidator { public function validate($protocol, Constraint $constraint) { if ((empty($protocol->getFoo())) && (empty($protocol->getBar()))) { $this->context->addViolationAt('foo', $constraint->message, array(), null); } } } 

Use the validator:

src / Acme / DemoBundle / Resources / config / validation.yml

 Acme\DemoBundle\Entity\AcmeEntity: constraints: - Acme\DemoBundle\Validator\Constraints\CheckTwoFields: ~ 
+4
source

All Articles