$this->createFormBuilder(null, array(
'validation_constraint' => new Collection(array(
'randominput' => array(
new NotBlank(),
new Email(),
new MyCustomConstraint()
)
))
->add('randominput', 'text');
提交结果(具有从html中删除的必需属性,带有萤火虫):
来自Email()约束的消息没有出现,因为该约束中存在一段代码,我认为这是NotBlank()约束的克隆/硬代码
if (null === $value || '' === $value) {
return;
}
我认为Email()约束应该是NotBlank()的子代...
如果NotBlank()发现违规,我不希望MyCustomConstraint()被执行。因此,如果可以使用某些选项,例如“ breakNextConstraintExecutionOnFirstViolation” => true,那将是很好的选择。因此,如果我为一个字段设置10个约束,而第3个约束设置了违规,则接下来的7个约束将不会执行。
如果symfony2中不存在这种逻辑/选项,那么可以从MyCustomConstraint类访问'validation'服务并重用现有约束,但不为每个新约束编写硬代码,那就很好了:
class MyCustomConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
// use the validator to validate the value, not hardcode
if (count( $this->get('validator')->validateValue(
$value,
new NotBlank()
)) > 0)
{
return;
}
$this->context->addViolation('MyCustomConstraint Message...');
}
}
所以我的问题是:我应该怎么做才能防止一个提交多个违规消息,并且不要在每个新的约束硬编码中使用它?
P.S。在我以前的项目中(不在symfony上),我制作了仅显示一条错误消息的表格。因此,用户一个接一个地填写字段,只看到一个错误,但没有提交表单,并且每个字段都充满红色错误(并吓some了一些用户)。但现在至少我想解决此问题。