2

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".

2

1 Answer 1

1

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('...');

Sign up to request clarification or add additional context in comments.

5 Comments

I've added the code and edited DependencyInjection/Configuration.php, but now I'm getting 'There is no extension able to load the configuration...'. Am I missing something?
Can you give me the complete error? Because I want to know which extension he can't load.
Why did you edit DependencyInjection/Configuration.php? Because if you place the code in your services.yml it should be loaded already.
I've removed it but I've got a similar problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.