'session flash message doesn't work when I add it in submitted form action with condition symfony
I have an edit page of my user object, so when the user have role admin and he is the connected user he doesn't have access to change his own role admin so I disabled the input of role when the user try to access the page to modify his own information, but before the form isSubmitted() I remove the disabled character from the input of role to access the content of the input in the action and check with a condition if this user try to change his password and display an error message
the edit action :
#[Route('/edit/{id}', name: 'app_user_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, User $user, UserRepository $userRepository): Response
{
$session = $this->requestStack->getSession();
$session->set('key' ,$user->getId());
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
//dd($form->isValid());
if ($form->isSubmitted() && $form->isValid() ) {
if (in_array('ROLE_ADMIN',$user->getRoles()) && $user === $this->getUser()) {
if($user->getRoles() != ['ROLE_ADMIN','ROLE_USER']) {
$session = $request->getSession();
$session->getFlashBag()->add('error', 'You cannot change your role!');
} else{
$userRepository->add($user);
return $this->redirectToRoute('app_user_index', [], Response::HTTP_SEE_OTHER);
}}
}
return $this->renderForm('user/edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
the message in twig page
{% for message in app.flashes('error') %}
<div class="alert alert-success">
{{ message }}
</div>
{% endfor %}
Solution 1:[1]
The requestStack services is made to retrieve the request in a services. But you can't attach information in to it. If you wan't to add flashMessages to the request you can use the build in addFlash() method of your AbstractController.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | matheo |