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?