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 AcmeDemoBundleValidatorConstraints;
use SymfonyComponentValidatorConstraint;
/**
* @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 AcmeDemoBundleValidatorConstraints;
use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;
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
AcmeDemoBundleEntityAcmeEntity:
constraints:
- AcmeDemoBundleValidatorConstraintsCheckTwoFields: ~
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…