<?php
namespace App\Form\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use App\Entity\User;
class AddPasswordFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
// Tells the dispatcher that you want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return [
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::PRE_SUBMIT => 'preSubmit',
FormEvents::POST_SUBMIT => 'postSubmit',
];
}
private function addField(Form $form, bool $requiredPassword) {
$form->add('password', RepeatedType::class, array(
'required' => $requiredPassword,
'type' => PasswordType::class,
'invalid_message' => 'Las contraseñas deben ser iguales.',
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repetir Password'),
'attr' => array('autocomplete' => 'new-password', 'placeholder' => 'Contraseña'),
));
}
public function postSubmit(FormEvent $event): void
{
//return object
$data= $event->getData();
$form = $event->getForm();
}
public function preSubmit(FormEvent $event): void
{
$data= $event->getData();
$form = $event->getForm();
//$form->remove('password');
}
public function preSetData(FormEvent $event): void
{
// Return object
$data= $event->getData();
$form = $event->getForm();
//dd($form->isSubmitted());
$requiredPassword = (!$data || null === $data->getId()) ? true : false ;
$this->addField($form, $requiredPassword);
}
}