I have built a FormType to change the users password. When i check whether the oldPassword field matches with the users old password, i add a FormError to this field.
In case the given old Password is wrong, it works and the error is displayed.
But if the given oldPassword is correct, the line where i add my FormError causes a logout, the password is not changed and i get redirected to the login page.
When i comment this line out, changing the password works. (Not depending on the oldPassword field)
The builder from my UserPasswordType:
$builder
->add('passwordOld', PasswordType::class, [
'mapped' => false,
'label' => 'Aktuelles Passwort'
])
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'invalid_message' => 'Die Passwortfelder müssen übereinstimmen.',
'required' => true,
'first_options' => ['label' => 'Neues Passwort'],
'second_options' => ['label' => 'Wiederholen'],
])
->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $formEvent) {
/** @var User $user */
$user = $formEvent->getData();
if (!$this->userPasswordEncoder->isPasswordValid($user,
$formEvent->getForm()->get('passwordOld')->getData())) {
$formEvent->getForm()->get('passwordOld')->addError(new FormError('Passwort ist falsch.'));
}
$user->setPassword($this->userPasswordEncoder->encodePassword($user, $user->getPassword()));
})
->add('submit', SubmitType::class);
My Controller:
/**
* @Route("/settings", name="app_settings")
* @param Request $request
* @param ObjectManager $objectManager
* @param UserInterface $user
* @return Response
*/
public function __invoke(Request $request, ObjectManager $objectManager, UserInterface $user): Response
{
$form = $this->createForm(UserPasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$objectManager->flush();
}
return $this->render('user/settings.html.twig', [
'form' => $form->createView()
]);
}
My Repository: https://gitlab.com/user010101/simple-timelock/tree/master/app