2013-05-06 28 views
0

我正在写一个忘记密码表单,并且使用PHP验证(而不是YML),我试图首先检查电子邮件地址是否存在。Symfony验证器与教义查询

我想我主要是在那里,但我似乎无法在验证器内部运行一个Doctrine查询。这是我到目前为止:

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; 
    } 
} 

我得到“未定义的属性 - 容器”。

+0

也许这可以帮助你:http://php-and-symfony.matthiasnoback.nl/2011/11/symfony2-creating-a-validator-with-dependencies-make-it-a-service/ – 2013-05-06 12:31:34

+0

谢谢,但它没有显示如何在那里得到一个Doctrine查询 – James 2013-05-06 12:37:54

回答

0

只是传递学说服务验证这样的:

protected $doctrine; 

    public function __construct($doctrine) { 
     $this->doctrine = $doctrine; 
    } 

,比你services.yml函数:$ this-:

my_service.my_constraint: 
     class: MyCompany\MyBundleBundle\Validator\Constraints\MyValidator 
     arguments: 
      - '@doctrine' 
     tags: 
      - { name: validator.constraint_validator, alias: my_name } 

,然后你可以在你的验证像做> doctrine-> getRepository( '...');

+0

我已经添加了代码并编辑了DependencyInjection/Configuration.php,但是现在我得到'没有可以加载配置的扩展......'。我错过了什么吗? – James 2013-05-06 13:19:54

+0

你能给我完整的错误吗?因为我想知道他无法加载哪个扩展。 – NoScope 2013-05-06 13:29:11

+0

看看http://www.lifemirror.org/users/forgotten – James 2013-05-06 13:31:04