Symfony Inject Entity Manager to Custom Validator
Asked Answered
P

1

8

In my symfony application i need a custom validation constraint, which should check if an email is unique. This Constraint should be used as an annotation.

I followed the guideline from the symfony cookbooks, but i get exception:

Attempted to load class "unique.email.validator" from the global namespace. Did you forget a "use" statement?

This is the code i have in my Unique Email Constraint class:

<?php

namespace MyApp\AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* Class UniqueEmail
* @package MyApp\AppBundle\Validator\Constraints
* @Annotation
*/
class UniqueEmail extends Constraint
{
  public $message = 'The Email already exists.';

  public function validatedBy()
  {
      return 'unique.email.validator';
  }
}

And this is the code from my unique EmailValidator:

namespace MyApp\AppBundle\Validator\Constraints;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UniqueEmailValidator extends ConstraintValidator
{
   /**
    * @var EntityManager
    */
   protected $em;

   public function __construct(EntityManager $entityManager)
   {
      $this->em = $entityManager;
   }

  public function validate($value, Constraint $constraint)
  {
      $repository = $this->em->getRepository('AppBundle:Advertiser');
      $advertiser = $repository->findOneBy(array(
          'email' => $value
      ));

      if ($advertiser) {
          $this->context->buildViolation($constraint->message)
              ->addViolation();
      }
  }
} 

And last but not least my services.yml:

   services:
       unique.email.validator:
           class: MyApp\AppBundle\Validator\Constraints\UniqueEmailValidator
           arguments:
               entityManager: "@doctrine.orm.entity_manager"
           tags:
               - { name: validator.constraint_validator, alias:      unqiue.email.validator }

Does anyone have any idead how to solve it?

Patellate answered 11/4, 2015 at 13:47 Comment(2)
Use "app/console container:debug unique.email.validator" to verify your services file is being loaded.Kotta
Do you really have to add the validatedBy() function in your UniqueEmail Class? My understanding was it is unnecessary symfony.com/doc/master/validation/…Guiana
A
7

In your services.yml the alias is misspelled: 'unqiue.email.validator' instead of 'unique.email.validator'

Agnail answered 28/7, 2015 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.