我试图为我的某个实体设置自定义constrait验证,constrait验证需要检查数据表以检查并验证该字段。
我点了这个链接:https://symfony.com/doc/2.8/validation/custom_constraint.html但它没有说明如何使用YAML为我的实体设置constrait验证。
将constrait验证设置为类,symfony会抛出一个错误,指出该类需要传递一个EntityManager实例。
这是我的验证员:
namespace Acme\BundleibBundle\Validator\Constraints;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class IsNotDayOff extends ConstraintValidator
{
private $em;
public $message = 'Impossible the send this day.';
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
public function validate($value, Constraint $constraint)
{
$repository = $em->getRepository('AcmeRibBundle:DayOff');
$isDayOff = $repository->findOneByDate($value);
if ($isDayOff) {
$this->context->buildViolation($constraint->message)
->addViolation();
}
}
}
这是我的服务配置:
validator.is_not_day_off:
class: Acme\Bundle\RibBundle\Validator\Constraints\IsNotDayOff
attributes:
- "@doctrine.orm.entity_manager"
tags:
- { name: validator.constraint_validator, alias: "validator.is_not_day_off" }
我也试试这个:
validation.yml
Acme\Bundle\RibBundle\Entity\Address:
properties:
deliveryDate:
- validator.is_not_day_off: ~
但也是抛出和异常。
有些帮助吗?
答案 0 :(得分:2)
您似乎只有一个验证工具,并且您正试图将其作为您房产的约束条件。
你应该区分班级:
您在validation.yml
中出现的约束class IsNotDayOff extends Constraint
{
public $message = 'your error message';
public function validatedBy()
{
//return your validator class
}
}
您的验证者必须在services.yml
中声明为服务class IsNotDayOffValidator extends ConstraintValidator
{
//your own logic...
}