src/Form/RegistrationFormType.php line 20
<?php
namespace App\Form;
use App\Entity\UserEntity;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Validator\Constraints\Callback;
class RegistrationFormType extends AbstractType
{
private $translator;
private $entityManager;
public function __construct(TranslatorInterface $translator, EntityManagerInterface $entityManager)
{
$this->translator = $translator;
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('username', TextType::class,
[
'label' => false,
'attr' => ['class' => 'w-100 mb-2 p-2 border border-gray-300 rounded-md', 'placeholder' => $this->translator->trans('login_username_placeholder')],
])
->add('email', EmailType::class, [
'label' => false,
'attr' => ['class' => 'w-100 mb-2 p-2 border border-gray-300 rounded-md', 'placeholder' => $this->translator->trans('login_email_placeholder')],
'constraints' => [
new NotBlank([
'message' => $this->translator->trans('email_unformated'),
]),
new Email([
'message' => $this->translator->trans('email_unformated'),
]),
]
])
->add('plainPassword', PasswordType::class, [
'mapped' => false,
'label' => false,
'attr' => ['autocomplete' => 'new-password', 'class' => 'w-100 mb-2 p-2 border border-gray-300 rounded-md', 'placeholder' => $this->translator->trans('login_password_placeholder')],
'constraints' => [
new NotBlank([
'message' => $this->translator->trans('password_unformated'),
]),
new Length([
'min' => 8,
'minMessage' => $this->translator->trans('password_unformated'),
'max' => 4096,
]),
],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => UserEntity::class,
'constraints' => [
new Callback([$this, 'validateUniqueEmail']),
],
]);
}
public function validateUniqueEmail($object, ExecutionContextInterface $context)
{
$existingUser = $this->entityManager->getRepository(UserEntity::class)->findOneBy(['email' => $object->getEmail()]);
if ($existingUser) {
$context->buildViolation($this->translator->trans('email_exists'))
->atPath('email')
->addViolation();
}
}
}