Inject doctrine entityManager to symfony validator constraint

66 views
Skip to first unread message

Nima Sadjadi

unread,
Oct 17, 2019, 1:21:06 AM10/17/19
to doctrine-user
Hello,

I created custom symfony validator and constraint for standalone use, not framework. I wrote this code to inject doctrine entity manager to validator class.

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Validator\ContainerConstraintValidatorFactory;

$container = new ContainerBuilder();
$container
->register('customEmailUniqueEntity', 'EmailExistsValidator')
->addArgument($em);
$validatorBuilder = Validation::createValidatorBuilder();
$validatorBuilder->setConstraintValidatorFactory(
new ContainerConstraintValidatorFactory($container)
);

$validator = $validatorBuilder->getValidator();
$violations = $validator->validate('email address', [
new EmailExists()
]);

if (0 !== count($violations)) {
// there are errors, now you can show them
foreach ($violations as $violation) {
echo $violation->getMessage().'<br>';
}
}

With this code both dependency injection and validation/constraint works fine, but is there a trick to have this custom constraint as 'constraint' array argument within form builder rather than validating it manually as above?

->add('email', EmailType::class, [
'constraints' => [
new Assert\Email(['message' => 'invalid.email', 'mode' => 'strict', 'normalizer' => 'trim']),
new Assert\EmailExists($em),
],
]);

With code above I cannot pass $em to the constructor of my custom Validator. Any trick possible? Is here someone who used doctrine with standalone symfony form/validator?

Reply all
Reply to author
Forward
0 new messages