Symfony 2 - 表单错误 - 获取错误类型
Symfony 2 - Form errors - get error type
表单提交后是否可以检查违反了哪个约束?
我想在提交后执行特定操作,但前提是出现特定错误(自定义约束)。
是的,你可以。这不是一个非常干净的方式(因为它是一个非常自定义的表单用例),但它是可能的。
这是一个简单的代码示例。它可能无法处理某些边缘情况,但适用于我的表单:
//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;
}
}
表单提交后是否可以检查违反了哪个约束? 我想在提交后执行特定操作,但前提是出现特定错误(自定义约束)。
是的,你可以。这不是一个非常干净的方式(因为它是一个非常自定义的表单用例),但它是可能的。
这是一个简单的代码示例。它可能无法处理某些边缘情况,但适用于我的表单:
//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;
}
}