src/Form/EventListener/AddPasswordFieldSubscriber.php line 63

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  5. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  6. use Symfony\Component\Form\Extension\Core\Type\TextType;
  7. use Symfony\Component\Form\Form;
  8. use Symfony\Component\Form\FormEvent;
  9. use Symfony\Component\Form\FormEvents;
  10. use App\Entity\User;
  11. class AddPasswordFieldSubscriber implements EventSubscriberInterface
  12. {
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         // Tells the dispatcher that you want to listen on the form.pre_set_data
  16.         // event and that the preSetData method should be called.
  17.         return [
  18.             FormEvents::PRE_SET_DATA => 'preSetData',
  19.             FormEvents::PRE_SUBMIT   => 'preSubmit',
  20.             FormEvents::POST_SUBMIT => 'postSubmit',
  21.         ];
  22.     }
  23.     private function addField(Form $formbool $requiredPassword) {
  24.         $form->add('password'RepeatedType::class, array(
  25.             'required' => $requiredPassword,
  26.             'type' => PasswordType::class,
  27.             'invalid_message' => 'Las contraseñas deben ser iguales.',
  28.             'first_options'  => array('label' => 'Password'),
  29.             'second_options' => array('label' => 'Repetir Password'),
  30.             'attr' => array('autocomplete' => 'new-password''placeholder' => 'Contraseña'),
  31.         ));
  32.     }
  33.     public function postSubmit(FormEvent $event): void
  34.     {
  35.         //return object
  36.         $data$event->getData();
  37.         $form $event->getForm();
  38.     }
  39.     public function preSubmit(FormEvent $event): void
  40.     {
  41.         $data$event->getData();
  42.         $form $event->getForm();
  43.         //$form->remove('password');
  44.     }
  45.     public function preSetData(FormEvent $event): void
  46.     {
  47.         // Return object
  48.         $data$event->getData();
  49.         $form $event->getForm();
  50.         //dd($form->isSubmitted());
  51.         $requiredPassword = (!$data || null === $data->getId()) ? true false ;
  52.         $this->addField($form$requiredPassword);
  53.     }
  54. }