Symfony. Validate an object based on its previous version

How to validate an object using the Validator component of Symfony and taking into account its previous version

Photo by Icons8 team on Unsplash

Defining a “Constraint class”

Since Symfony and the Validator component allow us to solve the case we have raised with one of the Constraints that we have by default, what we will have to do is create our own.

  • The $message property can have what you want and will be the error message that the form will contain in case the new title does not pass the validation.
  • And finally and most importantly, we need to declare this Constraint as a CLASS_CONSTRAINT since we will subsequently need to receive in the validator associated with this Constraint the object of the MyEntity class and not the title property.

Defining a “Validator” class

That said, the next thing we will do is write the validator of this Constraint. To do this, we will create a class called TitleLengthValidator within it where we create the constraint.

  • The Constraint that is being validated

¡Wow! Please, clarify UnitOfWork concept

Imagine we want to edit objects of the MyEntity class. What we will have done in our controller will have been to retrieve it by id through the associated repository, create a form of the MyEntityFormType class by passing said object and associate that form to the Request through the handleRequest method:

Let’s continue with the TitleLengthValidator class

Now I think it is clearer why we need to declare the constraint as CLASS_CONSTRAINT, because what we need is to receive the object in the validator in order to be able to recover it through the UnitOfWork.

Associate the TitleLength constraint with the entity

And the last step will be to associate our constraint with the entity. I will use annotations for convenience, for which we will go to src/Entity/MyEntity.php and add what you see below:

¿Quieres recibir más artículos como este?

Suscríbete a nuestra newsletter:

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store