0
是否可以在表单提交后检查违反了哪个约束条件? 我想在提交后做出特定的操作,但只有在出现特定的错误时(自定义约束)。Symfony 2 - 表单错误 - 获取错误类型
是否可以在表单提交后检查违反了哪个约束条件? 我想在提交后做出特定的操作,但只有在出现特定的错误时(自定义约束)。Symfony 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;
}
}