<?php
// src/Form/PasswordForgetType.php
namespace App\Form;
use Sulu\Bundle\CommunityBundle\Validator\Constraints\Exist;
use Sulu\Bundle\SecurityBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PasswordForgetType extends AbstractType
{
private $flashbag;
public function __construct(FlashBagInterface $flashbag)
{
$this->flashbag = $flashbag;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('email_username', TextType::class, [
'constraints' => new Exist([
'columns' => ['email', 'username'],
'entity' => $options['user_class'],
'groups' => 'password_forget'
]),
'label_attr' => ["class" => "fs14 fw400 lh24"],
'label' => "Email *",
'attr' => ['placeholder' => 'you@example.com'],
'required' => true
]);
$builder->add('submit', SubmitType::class, [
'label' => 'Valider'
]);
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
if (!$form->isValid()) {
$this->addValidationErrorsToFlashBag($form, $this->flashbag);
}
});
}
private function addValidationErrorsToFlashBag(FormInterface $form, FlashBagInterface $flashBag)
{
$errors = $form->getErrors(true);
foreach ($errors as $error) {
$newErrorMessage = '';
if ($error->getMessageTemplate() === "The value \"%string%\" was not found.") {
$wrongEmail = $error->getMessageParameters()["%string%"];
$newErrorMessage = "La valeur \"$wrongEmail\" n'existe pas.";
}
$flashBag->add('error', $newErrorMessage);
}
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'user_class' => User::class,
'validation_groups' => ['password_forget'],
]);
}
}