Search code examples
symfonyormsymfony-3.3symfony-validatorsymfony3.x

Symfony validation callback


I'm trying to validate my entity via static callback.

I was able to make it work following the Symfony guide but something isn't clear to me.

public static function validate($object, ExecutionContextInterface $context, $payload)
{
    // somehow you have an array of "fake names"
    $fakeNames = array(/* ... */);

    // check if the name is actually a fake name
    if (in_array($object->getFirstName(), $fakeNames)) {
        $context->buildViolation('This name sounds totally fake!')
            ->atPath('firstName')
            ->addViolation()
        ;
    }
}

It works fine when I populate my $fakeNames array but what if I want to make it "dynamic"? Let's say I want to pick that array from the parameters or from the database or wherever. How am I supposed to pass stuff (eg. the container or entityManager) to this class from the moment that the constructor doesn't work and it has to be necessarily static?

Of course my approach may be completely wrong but I'm just using the symfony example and few other similar issues found on the internet that I'm trying to adapt to my case.


Solution

  • You can create a Constraint and Validator and register it as service so you can inject entityManager or anything you need, you can read more here:

    https://symfony.com/doc/2.8/validation/custom_constraint.html

    or if you are on symfony 3.3 it is already a service and you can just typehint it in your constructor: https://symfony.com/doc/current/validation/custom_constraint.html