src/Form/Type/LoginType.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\Form\Type;
  3. use Symfony\Component\Form\AbstractType;
  4. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  5. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  6. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  7. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  8. use Symfony\Component\Form\Extension\Core\Type\TextType;
  9. use Symfony\Component\Form\FormBuilderInterface;
  10. use Symfony\Component\Form\FormError;
  11. use Symfony\Component\Form\FormEvent;
  12. use Symfony\Component\Form\FormEvents;
  13. use Symfony\Component\OptionsResolver\OptionsResolver;
  14. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  15. final class LoginType extends AbstractType
  16. {
  17.     /**
  18.      * @var AuthenticationUtils
  19.      */
  20.     private $authenticationUtils;
  21.     public function __construct(AuthenticationUtils $authenticationUtils)
  22.     {
  23.         $this->authenticationUtils $authenticationUtils;
  24.     }
  25.     /**
  26.      * {@inheritdoc}
  27.      */
  28.     public function buildForm(FormBuilderInterface $builder, array $options): void
  29.     {
  30.         $builder
  31.             ->add('email'TextType::class, ['label' => 'Email'])
  32.             ->add('password'PasswordType::class, ['trim' => true])
  33.             ->add('_remember_me'CheckboxType::class, [
  34.                 'label_attr' => ['class' => 'switch-custom'],
  35.                 'required' => false,
  36.             ])
  37.             ->add('_target_path'HiddenType::class)
  38.             ->add('button-submit'SubmitType::class, ['label' => 'Log In']);
  39.         $authUtils $this->authenticationUtils;
  40.         $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($authUtils): void {
  41.             $error $authUtils->getLastAuthenticationError();
  42.             if (null !== $error) {
  43.                 $event->getForm()->addError(new FormError($error->getMessage()));
  44.             }
  45.             $event->setData(array_replace((array) $event->getData(), [
  46.                 'email' => $authUtils->getLastUsername(),
  47.             ]));
  48.         });
  49.     }
  50.     /**
  51.      * {@inheritdoc}
  52.      */
  53.     public function configureOptions(OptionsResolver $resolver): void
  54.     {
  55.         $resolver->setDefaults([
  56.             'csrf_protection' => true,
  57.             'csrf_field_name' => '_csrf_token',
  58.             'csrf_token_id' => 'authenticate',
  59.         ]);
  60.     }
  61.     public function getBlockPrefix()
  62.     {
  63.         return '';
  64.     }
  65. }