1

Is it possible to check which Constraint was violated after form submit? I want to make specific action after submiting but only if particular error appears (custom constraint).

1 Answer 1

2

Yes you can. It's not a very clean way (since it's a pretty custom use case of forms), but it's possible.

Here's a simple code sample. It may not handle some edge cases, but works for my forms:

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

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.