Symfony 4/5 Password Reset

Here I’m sharing how to reset the password of a user in symfony 4.

UserPasswordResetType.php

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class UserPasswordResetType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options' => array('label' => 'New Password'),
                'second_options' => array('label' => 'Repeat New Password')
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

reset-password.html.twig

{% extends "base.html.twig" %}

{% block body %}
   
    {{ form_start(form) }}
                  
    {{ form_label(form.plainPassword.first) }}
    {{ form_widget(form.plainPassword.first) }}
                  
    {{ form_label(form.plainPassword.second) }}
    {{ form_widget(form.plainPassword.second) }}
                   
    <input type="submit" value="Submit">

    {{ form_end(form) }}
  
{% endblock %}

EmployeeController.php

public function resetPassword(Request $request, User $user, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $form = $this->createForm(UserPasswordResetType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // encode the plain password
            $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    $form->get('plainPassword')->getData()
                )
            );

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            $this->addFlash('success', "Password reset successfully");
            return $this->redirectToRoute('your_redirect_path');
        }

        return $this->render('reset-password.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }

If you need password change feature simply add field for old password in form and verify old password before resetting to new password.

cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *