I'm trying to validate one unique field using Symfony validation engine. I've created validation constraints and everything works fine but I want to have validated entity (or POST data) in my validator. Here is what it looks for now:
<?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;
}
}
Method isEanUnique will return false when updating the product becouse it contains ean within itself and it's right. What I need to do to fix?
$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());
But I don't know how to bring $this->product here... Any ideas?