I am using EasyAdminBundle and wanted to create change password functionality for admin panel. Everything works correctly, however there is a problem, that form doesn't show errors, when RepeatedType fields are not the same and when oldPassword is incorrect. Errors are correctly being sent from formType to controller, however the twig doesn't display them. ChangeAdminPasswordType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('oldPassword', PasswordType::class, [
'constraints' => [
new NotBlank(),
new Length(['min' => 4])
],
])
->add('newPassword', RepeatedType::class, [
'type' => PasswordType::class,
'error_bubbling' => true,
'invalid_message' => 'The password fields must match.',
'first_options' => ['label' => 'New Password'],
'second_options' => ['label' => 'Repeat New Password'],
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'btn btn-primary'],
])
;
}
ChangeAdminPasswordController
public function changeAdminPassword(Request $request): Response
{
$ex = new ChangeAdminPasswordDto();
$form = $this->formFactory->create(ChangeAdminPasswordType::class, $ex);
$view = $form->createView();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if (($this->changeAdminPassword)($this->getUser(), $form->getData())) {
return $this->redirectToRoute('admin_dashboard');
}
$form->addError(new FormError('Current password is not correct'));
}
return $this->render('bundles/EasyAdminBundle/changeAdminPassword.html.twig', [
'form' => $view,
]);
}
changAdminPassword.html.twig
{% extends '@EasyAdmin/layout.html.twig' %}
{% block content_title %}
<div >
<h1 >
Change password
</h1>
</div>
{% endblock %}
{% block main %}
{{ form_errors(form) }}
{{ form_start(form) }}
<div >
<div >
{{ form_label(form.oldPassword) }}
<div >
{{ form_widget(form.oldPassword, { 'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div >
{{ form_label(form.newPassword.first) }}
<div >
{{ form_widget(form.newPassword.first, { 'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div >
{{ form_label(form.newPassword.second) }}
<div >
{{ form_widget(form.newPassword.second, { 'attr': {'class': 'form-control'}}) }}
</div>
</div>
</div>
<div >
{{ form_row(form.save) }}
</div>
{{ form_end(form) }}
{% endblock %}
CodePudding user response:
You're creating the form view before the submission here $view = $form->createView();
. Any error messages wont be rendered after any validations...
Change this:
return $this->render('bundles/EasyAdminBundle/changeAdminPassword.html.twig',
[
'form' => $view,
]);
To this:
return $this->render('bundles/EasyAdminBundle/changeAdminPassword.html.twig',
[
'form' => $form->createView(),
]);