Search code examples
phpsymfonysymfony-formssymfony-validator

Symfony 2.6 form validation and error messages


I am fairly new to Symfony. I have written the below code to validate and return error messaged if validation failed. But I was able to only get the error message not the field which failed the validation. Below is my code:

if ($request->isXmlHttpRequest()) {

        if ($form->isValid()) {
            //do something here
        }

        $errors = $this->get('my_form')->getErrorMessages($form);
        return new JsonResponse(['errors' => $errors], 400);
}

Can someone please tell me how can I also get the field name along with the error message.

Thanks


Solution

  • In order to get all the Errors of a form use $form->getErrors($deep=true, $flatten=true) so converting the errors to an array with names as field names and keys as messages will be something like:

    $errors = $form->getErrors(true, true);
    $errorArray = array();
    foreach($errors as $e){
      //get the field that caused the error
      $field = $e->getOrigin();
      $errorArray[$field->getName()] = isset($errorArray[$field->getName()]) ? $errorArray[$field->getName()] : array();
      $errorArray[$field->getName()][] = $e->getMessage();
    }