我有一个班级
Class SubjectSegment{
/**
*@CustomAssert\MyCitizenshipNumber()
*/
private $citizenshipNumber;
/**
*@CustomAssert\MyDate()
*/
private $citizenshipNumberIssuedDate;
}
如果出现citizenshipNumber,我真正想做的是有效的citizenshipNumberIssuedDate ......
实现这一目标的最佳方式是什么
答案 0 :(得分:3)
您好,您应该查看http://symfony.com/doc/current/reference/constraints/Callback.html
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;
/**
* @Assert\Callback(methods={"isCitizenDateValid"})
*/
Class SubjectSegment{
/**
*@CustomAssert\MyCitizenshipNumber()
*/
private $citizenshipNumber;
/**
*@CustomAssert\MyDate()
*/
private $citizenshipNumberIssuedDate;
public function isCitizenDateValid(ExecutionContext $context)
{
//Do your validation here for your exemple :
if(null === $this->citizenshipNumber && null === $this->citizenshipNumberIssuedDate) {
$context->addViolationAtSubPath('citizenshipNumberIssuedDate', 'The date is required', array(), null);
}
}
}
答案 1 :(得分:3)
Class SubjectSegment{
/**
*@CustomAssert\MyCitizenshipNumber()
*/
private $citizenshipNumber;
/**
*@CustomAssert\MyDate(group={"is_my_citizenship_number"})
*/
private $citizenshipNumberIssuedDate;
public function getGroupSequence(){
$sequence = ['SubjectSegment'];
if(null != $this->CitizenshipNumber){
$sequence[] = 'is_my_citizenship_number';
}
return $sequence;
}
}
验证
$violations = $container->get('validator')->validate($segment = new SubjectSegmet(), null,$segment->getGroupSequence() );
答案 2 :(得分:2)
您可以通过两种方式对其进行归档:
1)回调验证器(通过类方法验证)
2)使用class constraint validator
我建议采用第二种方式,因此您必须将验证器配置/设置为类范围,如:
/**
* @Annotation
*/
class MyCitizenshipNumber extends Constraint {
...
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
因此您可以访问所有类字段成员
请记住将验证器置于类定义之上,如:
/**
*@CustomAssert\MyCitizenshipNumber()
*/
Class SubjectSegment{
private $citizenshipNumber;
/**
*@CustomAssert\MyDate()
*/
private $citizenshipNumberIssuedDate;
}
希望这个帮助