Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error message after entity validation

I'm trying to get a clean error message after validating my Subscribe Entity :

/**
 * Subscribe
 * @UniqueEntity("email")
 * @ORM\Table(name="subscribe")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\SubscribeRepository")
 */
class Subscribe
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank()
     * @Assert\Email()
     * @ORM\Column(name="email", type="string", length=255, nullable=true, unique=true)
     */
    private $email;

After calling the validator service and test it with blank email:

   $validator = $this->get('validator');
   $errors = $validator->validate($email);
    if (count($errors) >0) {
    return new JsonResponse( (string)$errors);
      }

I got this message Object(AppBundle\Entity\Subscribe).email: This value must not be empty. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3). Any idea how to clean it ?

like image 548
famas23 Avatar asked May 28 '17 16:05

famas23


People also ask

What is entity validation error?

EntityValidationErrors is a collection which represents the entities which couldn't be validated successfully, and the inner collection ValidationErrors per entity is a list of errors on property level. These validation messages are usually helpful enough to find the source of the problem.

What is validation error message?

Validation errors typically occur when a request is malformed -- usually because a field has not been given the correct value type, or the JSON is misformatted.


1 Answers

try this:

           $validator = $this->get('validator');
           $errors = $validator->validate($email);
           if (count($errors) >0) {
                $messages = [];
                foreach ($errors as $violation) {
                     $messages[$violation->getPropertyPath()][] = $violation->getMessage();
                }
                return new JsonResponse($messages);
           }

In this way I have create an array of errors, where the key is the not valid field, you can change this logic and add only the name of the field in front of the error and return a simple string.

This code can works with all fields in the form

like image 171
Alessandro Minoccheri Avatar answered Nov 15 '22 04:11

Alessandro Minoccheri