我在自定义验证器约束方面遇到了一些问题。我想在我的实体TicketCode中验证字段代码。
但是当我使用if(form-> isValid)时没有调用验证器,我不明白为什么。
如果此代码对应,我的自定义Validator需要实体管理器检查数据库,否则验证器发送消息错误。
我的实体
<?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;
}
}
最后我的 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 }
如果您知道为什么我的验证器从未被调用过,请向我解释。
答案 0 :(得分:1)
您的函数名称 ValidatedBy()中有一个上限V.它应该是 validatedBy()。