0

I have the following Problem. I use Symfony Forms to Validate a JSON Request, that also works great. But i will also the thrown Errors in a more Json readable way.

Is it possible that i can get from the FormErrorIterator FormError for each Error the relevant Field name.

For Example:

formName.SubForm.Propertyname => 'MyErrorMessage'

the structure of the path could be also an Array.

1 Answer 1

1

If you want to retrieve the errors of your form in an array you could add and use this method in your controller :

private function getErrorMessages(\Symfony\Component\Form\Form $form) {
    $errors = array();

    foreach ($form->getErrors() as $key => $error) {
        if ($form->isRoot()) {
            $errors['#'][] = $error->getMessage();
        } else {
            $errors[] = $error->getMessage();
        }
    }

    foreach ($form->all() as $child) {
        if (!$child->isValid()) {
            $errors[$child->getName()] = $this->getErrorMessages($child);
        }
    }

    return $errors;
}

$errors will contain an array of errors and if a field has an error the field name will be used as a key in the array :

$errors['FIELD_NAME'] = ERROR_MSG.

Depending of your Symfony version you might need or want other versions of this method : Symfony2 : How to get form validation errors after binding the request to the form.

UPDATE

If your validation constraints are on a field of the Entity class, they will be in the errors array with a key based on the field name.

If your validation constraints are on the Entity class, the will be in the # key or numeric key depending if the form is root or not.

Entity class example

/**
 * @Assert\Callback("isValidName") <- this error will be in $errors['#']
 */
class Author
{
    /**
     * @Assert\NotBlank() <- this error will be in $errors['firstname']
     */
    public $firstname;
}

If you want only errors on field, you need to move all your Entity class asserts on the Entity fields.

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

3 Comments

This seems more a comment. You need to request further information to those who asked the question if you want to extract from the reference link a more specific (and useful) answer to report here.
I have updated my answer regarding your comment, it should be more accurate.
in your answer you are writing from errors that are inside "#". how is it posible to bind one of this errors to a form field?

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.