Reputation: 771
I'm writing a forgotten password form and, using PHP validation (as opposed to YML), I am trying to first of all check whether the e-mail address exists.
I think I'm mostly there but I can't seem to run a Doctrine query inside the validator. Here is what I have so far:
class EmailExistsValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
$em = $this->container->get('doctrine.orm.entity_manager');
$query = $em->createQuery('SELECT COUNT(id) FROM users WHERE email=:email')
->setParameter('email', $value);
$count = $query->getQuery()->getSingleScalarResult();
if ($count != 1) {
$this->setMessage($constraint->message);
return false;
}
return true;
}
}
I get "undefined property - container".
Upvotes: 2
Views: 1901
Reputation: 1819
Just pass the doctrine service to the validator like this:
protected $doctrine;
public function __construct($doctrine) {
$this->doctrine = $doctrine;
}
and than in your services.yml:
my_service.my_constraint:
class: MyCompany\MyBundleBundle\Validator\Constraints\MyValidator
arguments:
- '@doctrine'
tags:
- { name: validator.constraint_validator, alias: my_name }
and then you can do in your validator like: $this->doctrine->getRepository('...');
Upvotes: 1