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.

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
gigo1980
  • 3
  • 2

1 Answers1

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.

Community
  • 1
  • 1
HypeR
  • 2,186
  • 16
  • 22
  • 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. – gp_sflover Mar 13 '15 at 18:30
  • I have updated my answer regarding your comment, it should be more accurate. – HypeR Mar 13 '15 at 19:29
  • 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? – gigo1980 Mar 13 '15 at 20:12