我刚刚搬到 symfony 5 并感到困惑!我在 Symfony 4 中多次使用验证器做过同样的事情,但是现在将 EntityManagerInterface 依赖注入(inject)到自定义验证器中会产生此错误:
Too few arguments to function App\Validator\Constraints\UserUsernameConstraintValidator::__construct(), 0 passed in /var/www/appbaseV4/vendor/symfony/validator/ContainerConstraintValidatorFactory.php on line 52 and exactly 1 expected
验证器类如下:
<?php
namespace App\Validator\Constraints;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UserUsernameConstraintValidator extends ConstraintValidator
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* UserEmailValidator constructor.
* @param EntityManagerInterface $entityManager
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
/**
* @param mixed $value
* @param Constraint $constraint
*/
public function validate($value, Constraint $constraint) : void
{
if(!$constraint instanceof UserUsernameConstraint){
throw new UnexpectedTypeException($constraint,UserUsernameConstraint::class);
}
if(null === $value || '' === $value){
return;
}
if($value != $constraint->value){
/** @var UserRepository $repo */
$repo = $this->em->getRepository(User::class);
if($repo->findOneBy(['username'=>$value])){
$this->context->buildViolation($constraint->errorMessage)->setParameter('username',$value)->addViolation();
}
}
}
}
然后像往常一样在表单类型中使用它:
$builder
->add('username',TextType::class,[
'attr'=>[
'class'=>'form-control'
],
'required'=>true,
'constraints'=>[
new UserUsernameConstraint(),
new Length([
'min'=>6,
'max'=>20
]),
]
])
这里发生了什么?他们是否在 Symfony 5 中改变了这一点,因为它不像我使用 symfony 4 时通常那样注入(inject)实体管理器。
最佳答案
您似乎没有使用 default services.yaml configuration ,在这种情况下,您必须tag您使用 validator.constraint_validator
的约束验证器标签。检查 documentation for Constraint Validators with Dependencies或修复/更新您的 Automatic Service Loading在 config/services.yaml
.
关于php - Symfony 5 无法将 EntityManagerInterface 注入(inject)验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61209688/