Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Inject Entity Manager to Custom Validator

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?

like image 664
BloodandDeath Avatar asked Apr 11 '15 13:04

BloodandDeath


1 Answers

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

like image 137
Nicole Bartolini Avatar answered Oct 21 '22 19:10

Nicole Bartolini