I've just moved to symfony 5 and baffled! I've done this same thing with validators many times with Symfony 4, but now dependency injection of EntityManagerInterface into a custom validator produces this error:
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
The validator class is as follows:
<?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();
}
}
}
}
And then using it in the form type as i always do:
$builder
->add('username',TextType::class,[
'attr'=>[
'class'=>'form-control'
],
'required'=>true,
'constraints'=>[
new UserUsernameConstraint(),
new Length([
'min'=>6,
'max'=>20
]),
]
])
What's going on here? Have they changed this in Symfony 5 because it's just not injecting the entity manager like it normally does when i use symfony 4.