I have an entity ArticlePattern, which has a property pattern (string). I need to access the database to check if pattern is correct. So I would like to define a method ArticlePattern::isPatternValid() and add a constraint (using Doctrine’s annotation) which would check if isPatternValid is true during validation by Validator object.
From what I have read here and there it is not a good idea, to make an entity depended on service container, which mean I cannot access the doctrine service from inside ArticlePattern::isPatternValid().
So how can I make a custom validation constraint which need an access to the database? How do you deal with such situations which I think is very common seeing so many questions about accessing a service container from an entity class.
EDIT:
Ok, thanks guys, so the answer is a Custom Validation Constraint
A validator object can be:
Symfony\Component\Validator\ConstraintValidatorInterfaceSo what do you have to do?
validatedBy()method to return validator “name” (return 'my_validator';)Define a simple service in DIC:
EDIT
You’ve asked about multiple properties validation. In such a case you could create a validator that is related to the object rather to the property of the object.
In your constraint class define the target of that constraint (property / class):
Annotate validated class instead of property:
The validator itself looks pretty much the same as in case of validating a property: