表单提交后是否可以检查哪些约束被违反? 我希望在提交后进行特定操作,但仅在出现特定错误时(自定义约束)。
答案 0 :(得分:2)
是的,你可以。它不是一个非常干净的方式(因为它是一个非常自定义的表格用例),但它是可能的。
这是一个简单的代码示例。它可能无法处理一些边缘情况,但适用于我的表单:
//You can get errors from form like this:
$errors = $form->getErrors(true);
// Or like this if you want to check a particular field of your form
$errors = $form->get('someField')->getErrors(true);
//Now you have to iterate them and check
//if it's the error that you're looking for
foreach($errors as $error) {
//From the error you can get the constraint that caused it.
$constraint = $error->getCause()->getConstraint();
//Check if the constraint is the instace of the class
//that you're insterested in.
//It's ISBN validator in my example.
if($constraint instanceof Symfony\Component\Validator\Constraints\Isbn) {
// do anything you want.
break;
}
}