【问题标题】:Symfony validator with Doctrine query带有 Doctrine 查询的 Symfony 验证器
【发布时间】:2013-04-30 04:57:29
【问题描述】:

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

我想我大部分时间都在那里,但我似乎无法在验证器中运行 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;
    }
}

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

【问题讨论】:

标签: validation symfony doctrine


【解决方案1】:

只需像这样将原则服务传递给验证器:

protected $doctrine;

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

比在你的 services.yml 中:

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

然后您可以在验证器中执行以下操作: $this->doctrine->getRepository('...');

【讨论】:

  • 我已经添加了代码并编辑了 DependencyInjection/Configuration.php,但现在我得到'没有扩展能够加载配置......'。我错过了什么吗?
  • 你能给我完整的错误吗?因为我想知道他不能加载哪个扩展。
  • 为什么要编辑 DependencyInjection/Configuration.php?因为如果您将代码放在 services.yml 中,它应该已经加载了。
  • 我已将其删除,但我遇到了类似的问题。
猜你喜欢
  • 1970-01-01
  • 2011-11-06
  • 2023-03-20
  • 1970-01-01
  • 2019-03-19
  • 2014-07-07
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多