Inject doctrine entityManager to symfony validator constraint

Skip to first unread message

Nima Sadjadi

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

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();
->register('customEmailUniqueEntity', 'EmailExistsValidator')
$validatorBuilder = Validation::createValidatorBuilder();
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' => '', '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
0 new messages