Redirecting to different route with page render

#1

I have a below form on GET /email_login

<form method="post" action="@routes.LoginController.email_auth()"> 

which is POSTing data to /email_auth on submit.

I am rendering the page with a message in the email_auth() method like below-

if (username == null || username.isEmpty()) {
                return ok(email_login.render("Please enter an email address"));

The issue is, suppose I am on http://localhost:9000/email_login , from there I am POSTing the call to /email_auth
on submit the url is getting changed to http://localhost:9000/email_auth
Now , when the above code is getting encountered , the email_login page is getting rendered, but the url is not getting redirected.

I want the redirect("/email_login") to happen along with the UI render. How can I achieve this?

#2

you can use Redirect with Flash to show a message, like Redirect(routes.AuthController.login()).flashing("success" -> "New password sent to your email")
or
Redirect(routes.AuthController.login()).flashing("error" -> "No such email")
and in your view it could be like this:

@(loginForm: Form[UserForm])(implicit request: actions.UserRequest[Any], flash: Flash, messages: Messages)

///...///
@flash.get("success")
@flash.get("error")
//...//

not sure if I understood the question (how could you been redirected to POST action email_auth?) but hope it will help

#3

and also just noticed, you don’t need to check if username is empty manually using forms instead where you can specify constraints like @Required for your form class fields

https://www.playframework.com/documentation/2.7.x/JavaForms

and you can configure your inputs in view to show form errors and not redirecting with each error message

https://www.playframework.com/documentation/2.7.x/JavaFormHelpers