2017-06-02 8 views
0

フォーム送信後にどのConstraintが違反しているかを確認することはできますか? サブミット後に特定のアクションを実行したいのですが、特定のエラーが表示される場合(カスタム制約)に限ります。Symfony 2 - フォームエラー - エラータイプ

答えて

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

    } 
関連する問題