Conditional field validation that depends on another field
I need to change the validation of some field in a form. The validator is configured via a quite large yml file. I wonder if there is any way to do validation on two fields at once. In my case I have two fields that cannot be both empty. At least one has to be filled.
Unfortunately till now I just could see that the validation are defined on a per-field basis, not on multiple fields together.
The question is: is it possible in the standard yml configurations to perform the aforementioned validation?
thanks!
Solution 1:
I suggest you to look at Custom validator, especially Class Constraint Validator.
I won't copy paste the whole code, just the parts which you will 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 the 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: ~