Symfony2在验证约束中使用实体

时间:2014-03-16 16:59:16

标签: php sql validation symfony entities

我尝试使用Symfony验证引擎验证一个唯一字段。我已经创建了验证约束,一切正常,但我想在验证器中验证实体(或POST数据)。以下是它现在的样子:

<?php
    namespace Webrama\ProductBundle\Validator\Constraints;

    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
    use Doctrine\ORM\EntityManager;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\Translation\TranslatorInterface;

    class EanCodeValidator extends ConstraintValidator
    {
        private $entityManager;
        private $translator;
        /**
         * @param EntityManager $entityManager
         */
        public function __construct(EntityManager $entityManager, TranslatorInterface $translator)
        {
            $this->entityManager = $entityManager;
            $this->translator = $translator;
        }

... some logic ...

        private function isEanUnique($value)
        {
            $query = $this->entityManager->createQuery("SELECT p.id FROM WebramaProductBundle:Product p WHERE p.eanCode = :eanCode AND p.eanCode <> 0");
            $query->setParameter('eanCode', $value);

            $result = $query->execute();

            if(empty($result))
                return true;

            return false;
        }
    }

方法isEanUnique在更新产品时将返回false,因为它本身包含ean并且它是正确的。我需要做些什么来修复?

$query = $this->entityManager->createQuery("SELECT p.id FROM WebramaProductBundle:Product p WHERE p.eanCode = :eanCode AND p.eanCode <> 0 AND p.id <> :productId");
                $query->setParameter('eanCode', $value);
                        $query->setParameter('id', $this->product->getId());

但我不知道如何将$ this-&gt;产品带到这里......有什么想法?

1 个答案:

答案 0 :(得分:0)

anwser是文档...需要查看页面How to create custon validation constraint上的类Constraint Validator。我做错了是我试图通过这种方式强制执行类型提示:

public function validate(Product $product, Constraint $constraint)
{
        ...
}

应该只是:

public function validate($product, Constraint $constraint)
{
        ...
}