Symfony 2-表单错误-获取错误类型

Symfony 2-表单错误-获取错误类型,symfony,symfony-forms,Symfony,Symfony Forms,是否可以检查表单提交后违反了哪个约束? 我想在提交后执行特定操作,但仅当出现特定错误时(自定义约束)。可以。这不是一种非常干净的方式(因为这是一个非常定制的表单用例),但这是可能的 下面是一个简单的代码示例。它可能无法处理某些边缘情况,但适用于我的表单: //You can get errors from form like this: $errors = $form->getErrors(true); // Or like this if you want to

是否可以检查表单提交后违反了哪个约束?
我想在提交后执行特定操作,但仅当出现特定错误时(自定义约束)。

可以。这不是一种非常干净的方式(因为这是一个非常定制的表单用例),但这是可能的

下面是一个简单的代码示例。它可能无法处理某些边缘情况,但适用于我的表单:

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

    }