mardi 5 juillet 2016

Which are the recommended ways to show a form POST success message?

What is the recommended way in Symfony to show the user a success message after a one-time form action?

For example I have a credentials form containing 3 input fields: username, password and repeated password. Users shouldn't see this form again after a successful update as it would show up with two empty password fields which might confuse the user.

Now I see 2 ways to show the success message:

  • the old way: create a separate route, a controller and a view. Then on success redirect to that special route and show the success message (but not the form). This is how Stackoverflow does it.
  • Symfony's flashbag system (or any other session based variant): this is how I am doing it now, but I came up with it myself and am completely unsure if that is even close to a good solution:

I think, the first option is pretty clear, but I'll illustrate the second option (using Symfony's flashbag system and only one route/controller/view).

The controller looks like this:

public function editCredentialsAction(Request $obj_request)
{
    // ...

    if ($form->isSubmitted() && $form->isValid())
    {
        // ...

        // redirect to self (with flash message)
        $this->addFlash('success', 'Your credentials have been updated!');
        return $this->redirectToRoute('editCredentials');
    }
    else
    {
        // ...

        $isSuccessFlashAvailable = $this->get('session')->getFlashBag()->has('success');

        return $this->render( 'actions/member/editCredentials.html.twig',
                              array( 'form' => $form->createView(), 
                                     'isSuccess' => $isSuccessFlashAvailable));
    }
}

And the view (using Twig) will look like this:





For me that's working fine, with the following benefits:

  • the user will not see the form again (unless he clicks the link)
  • but when he reloads the page the flash message will be gone and the form will be there again
  • less work & less overhead

Is this a good way to do this?

Are there other ways (maybe better ones)?

Aucun commentaire:

Enregistrer un commentaire