我正在尝试构建一个验证程序,它将检查数据库中的某些值。为此,我需要在服务中注入entityManager,并为我的Validation方法提供别名,如Symfony官方文档中所述。
问题是,在完成本书的所有内容后,我仍然收到一条错误,说明entityManager为空:
捕获致命错误:传递给XXX的参数1 \ CommonBundle \ Validator \ Constraints \ IsSingleEntryValidator :: __ construct()必须是Doctrine \ ORM \ EntityManager的实例,没有给定,在/ var / www / XXX / vendor /中调用第71行的symfony / symfony / src / Symfony / Bundle / FrameworkBundle / Validator / ConstraintValidatorFactory.php已定义
我的服务:
/usr/local/Cellar/gcc/5.2.0/bin/g++-5 -o3 -fopenmp -DNDEBUG main.cpp \
PattersonInstance.cpp \
... \
-o RROTprog
验证器类:
XXX.validators.is_single_entry:
class: XXX\CommonBundle\Validator\Constraints\IsSingleEntryValidator
arguments:
- "@doctrine.orm.default_entity_manager"
tags:
- { name: validator.constraint_validator, alias: single_entry_validation }
使用验证器:
class IsSingleEntryValidator extends ConstraintValidator
{
/**
* @var EntityManager
*/
protected $em;
/**
* Constructor
*
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function validate($value, Constraint $constraint)
{
...
}
public function validateBy()
{
return 'single_entry_validation';
}
}
答案 0 :(得分:0)
@Ragdata - doctrine.orm.default_entity_manager Doctrine \ ORM \ EntityManager
我的代码实际上有2个错误。
调用validatedBy()函数
此功能应在 IsSingleEntry 类中调用,而不是 IsSingleEntryValidator
方法名称应该是不同的
我将方法称为 validateBy(),但正确的函数名称应为 validatedBy()
所以代码应该现在看起来像这样:
IsSingleEntry
class IsSingleEntry extends Constraint
{
public $message = "The value already exists in the database";
/**
* @return string
*/
public function validatedBy()
{
return 'single_entry_validation';
}
}
IsSingleEntryValidator
class IsSingleEntryValidator extends ConstraintValidator
{
/**
* @var EntityManager
*/
protected $em;
/**
* Construct
*
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* Validate
*
* @param mixed $value
* @param Constraint $constraint
*/
public function validate($value, Constraint $constraint)
{
$oActiveExists = $this->em->getRepository('DatabaseBundle:Languages')->findOneByIsPrimary(true);
if ($oActiveExists) {
$this->context->buildViolation($constraint->message)
->addViolation();
}
}
}