2
我有一些自定义验证器约束的问题。我想验证实体TicketCode中的字段代码。自定义验证器不在Symfony 2中调用
但是当我使用if(form-> isValid)时,不会调用验证器,我不明白为什么。
我的自定义验证器需要实体管理器与数据库进行检查,如果此代码对应,否则验证器将发送消息错误。
我的实体
<?php
namespace My\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use My\MyBundle\Validator as TicketAssert;
/**
* My\MyBundle\Entity\TicketCode
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="My\MyBundle\Entity\TicketCodeRepository")
*/
class TicketCode
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $code
*
* @ORM\Column(name="code", type="string", length=255)
* @TicketAssert:ValidCode(entity="TicketBundle:TicketCode", property="code")
*/
protected $code;
}
我的类约束
<?php
namespace My\MyBundle\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ValidCode extends Constraint
{
public $message = 'Code Invalide';
public $entity;
public $property;
public function ValidatedBy()
{
return 'my_ticket_validator';
}
public function requiredOptions()
{
return array('entity', 'property');
}
public function targets()
{
return self::CLASS_CONSTRAINT;
}
}
我的验证
<?php
namespace My\MyBundle\Validator;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ValidCodeValidator extends ConstraintValidator
{
private $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function isValid($value, Constraint $constraint)
{
$todayInObject = new \DateTime(); //Renvoit la date du jour
var_dump($todayInObject);
$ticketCode = $this->entityManager->getRepository('MyMyBundle:TicketCode')->findOneBy(array('code' => $constraint->property));
if ($ticketCode != null) {
if ($ticketCode->nbMaxUse != 0 && ($todayInObject >= $ticketCode->getDateBegin && $todayInObject <= $ticketCode->getDateEnd())) {
return true;
}
else {
$this->setMessage($constraint->message);
return false;
}
}
else {
$this->setMessage($constraint->message);
return false;
}
return false;
}
}
Finall y我的service.yml在我的包中。
parameters:
my_ticket.validator.validcode.class: My\MyBundle\Validator\ValideCodeValidator
services:
my_ticket.validator.validcode:
class: %my_ticket.validator.validcode.class%
arguments: [@doctrine.orm.entity_manager]
tags:
- { name: validator.constraint_validator, alias: my_ticket_validator }
如果您有任何想法,为什么我的验证器从未被调用过,请向我解释谢谢。
尝试在app/config/config.yml中放置service.yml文件的内容。如果这个工作,这意味着你没有从你的包的DI扩展文件中加载service.yml(参见如何操作:http://symfony.com/doc/current/cookbook/bundles/extension.html) 也,您是否尝试在实体注释中用“@TicketAssert \ ValidCode”替换“@TicketAssert:ValidCode”? – AdrienBrault 2012-07-07 10:35:24