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;
}
}