Dblock247
Dblock247

Reputation: 6755

Symfony API Entity Validation

I have a class with annotations for the validation.

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serialize;
use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Annotation\Link;

/**
 * @Serialize\ExclusionPolicy("all")
 * @Serialize\AccessType(type="public_method")
 * @Serialize\AccessorOrder("custom", custom = {"id", "name", "awardType", "nominations"})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\AwardRepository")
 * @ORM\Table(name="awards")
 * @Link("self", route = "api_awards_show", params = { "id": "object.getId()" })
 */
class Award extends Entity
{
    /**
     * @Serialize\Expose()
     * @Serialize\Type(name="string")
     * @Assert\Type(type="string")
     * @Assert\NotBlank(message="Please enter a name for the Award")
     * @Assert\Length(min="3", max="255")
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @Serialize\Expose()
     * @Serialize\Type(name="AppBundle\Entity\AwardType")
     * @Serialize\MaxDepth(depth=2)
     * @Assert\Valid()
     * @ORM\ManyToOne(
     *     targetEntity="AppBundle\Entity\AwardType",
     *     inversedBy="awards"
     * )
     */
    private $awardType;

    /**
     * @Serialize\Expose()
     * @Serialize\Type(name="ArrayCollection<AppBundle\Entity\Nomination>")
     * @Serialize\MaxDepth(depth=2)
     * @ORM\OneToMany(
     *     targetEntity="AppBundle\Entity\Nomination",
     *     mappedBy="award"
     * )
     */
    private $nominations;
}

I then validate that entity with the following:

    $validator = $this->get('validator');
    $errors = $validator->validate($entity);

    if (count($errors) > 0) {
        $apiProblem = new ApiProblem(
            400,
            ApiProblem::TYPE_VALIDATION_ERROR
        );

        $apiProblem->set('errors', ['testing', 'array']);

        throw new ApiProblemException($apiProblem);
    }

    $this->save($entity);

This works fine the problem is that i cant get the information on which fields have errors and their error message. $errors in this case seems to be of an unknown type which i cant seem to get the error messages for any fields.

How do i get the error messages of that object?

Upvotes: 1

Views: 1253

Answers (1)

chalasr
chalasr

Reputation: 13167

You can get the exact messages of the errors like this:

$errors = $validator->validate($entity);

if (count($errors) > 0) {
    $formattedErrors = [];
    foreach ($errors as $error) {
        $formattedErrors[$error->getPropertyPath()] = [
            'message' => sprintf('The property "%s" with value "%s" violated a requirement (%s)', $error->getPropertyPath(), $error->getInvalidValue(), $error->getMessage());
        ];
    }

    return new \Symfony\Component\HttpFoundation\JsonResponse($formattedErrors, 400);
}

For example, that could output:

[
    'field1' => 'The property "field1" with value "" violated a requirement (Cannot be null)',
    // ...
]

Upvotes: 2

Related Questions