2

I'm working on an platform which contains lot of page with form and i'm looking for a way to inject (DI) service in my Entity/Constraint Validator. I tried many way, but never managed to do 100% what i wanted it.

Let me explain en detail : my stack : Php 8.0, Symfony 5.4, Doctrine 2

To make it simple, i will take the example of create page Form.

The form is build with a dedicated FormType (let's say DogType). The Entiy related to this FormType is Dog I'm using static loader to load constraints loadValidatorMetadata()

The field dog_race has a constraint ChoiceType. The data of choice should be filled with a method from a service AnimalManager, method getRaces. The constructor of this service is also using DI to get some other service such as Logger etc.

So, i know we can do something like that :

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    [...]
    $metadata->addPropertyConstraints('dog_race',
        [
            new Assert\Choice([
                'callback' => [DogManager::class, 'getRaces'],
                'message'  => 'doc.incorrect_race'
            ])
        ]
    )
}

But this callback works only with static method. If i'm not mistaken, we can use only static loader, php attribut and annotation, right ? But in all cases, i don't see how i can inject a service for the constraint.

My question is, how can i inject my service DogManager to be used in the constraint ? If not possible, any recommendation/alternative to do something similar ?

I have the feeling i have to create custom constraint just to be able to inject my service.. :(

Thanks

Fabien Papet
  • 2,244
  • 2
  • 25
  • 52
Rady
  • 51
  • 3
  • 2
    Your feeling is right. You need a custom validator. The docs will walk your through with the details. It may seem a bit painful but once you get the first one working then it becomes easy. – Cerad May 10 '22 at 13:45
  • Same advice, it's not surprising to use a custom validator in this case and it's easy and fast to implement once you get the hang of it. You could either use a class validator and check your whole entity or use customs property constraints with field like dogRace. https://symfony.com/doc/current/validation/custom_constraint.html – Dylan KAS May 10 '22 at 14:22
  • ok, i will some test with custom constraint so. thanks for your answer :) – Rady May 11 '22 at 10:55

0 Answers0