Sunday, January 23, 2022

[FIXED] Is doctrine Entity validation enough?

Issue

I have an Entity class which already has constrains:

/**
* @ORM\Column(type="string", length=255)
*/
private $X;

/**
* @ORM\Column(type="integer")
*/
private $Y;

In my controller i'm getting post data from form and using setMethods on entity class:

$property = new PropertyEntity();
$property->setX($request->request->get('X'));
$property->setY($request->request->get('Y'));

next step - save to db.

Do I need to do additional validation on post data ? I though I need to use validation library but i'm not sure if it will only add unnecessary overhead since "@ORM" is already form type is already doing some validation. Any general idea how and where to write validation ?(pseudocode is enough)


Solution

Good question! ORM mapping map the PHP class to the doctrine metadata (Model). Assert is a mechanism to validate objects received from form (View/Controller).

This means that you can use assert on objects that are not entities or that you cannot use a mapped field in your formType

You can make validation in the annotation of the field. example:

/**
* @Assert\NotBlank
* @ORM\Column(type="string", length=255)
*/
private $X;
    
/**
* @Assert\NotBlank
* @ORM\Column(type="integer")
*/
private $Y;

Don't forget to add: use Symfony\Component\Validator\Constraints as Assert;

More validation constraints are in this link: https://symfony.com/doc/current/validation.html#basic-constraints



Answered By - y.iragui

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.