Question

public static Result authenticate() {
    Form<LoginForm> loginForm = form(LoginForm.class).bindFromRequest();

    if (loginForm.hasErrors()) {
        return ok(views.html.Account.index.render(loginForm));
    } else {
            String email = loginForm.get().email;
            User user = User.findByUsername(email);

            if (Hash.checkPassword(loginForm.get().password, user.passwordHash)) {
                // set session
                session("email", email);
                return redirect(routes.UserController.view(user.getId()));
            } else {
                return badRequest(views.html.Account.index.render(loginForm));
            }
        }
}

We use this code to authenticate users, but we'd like to display error-messages when something goes amiss during login (invalid username / password etc.). However, we can't really find any documentation on this online - as most of the documentation surrounding the use of flash for error messages is mostly for Play 1.x.

1) How can we add error messages to this log in functionality?

2) How can we access these error messages in the view?

3) How (in general) does the form class in Play! handle the creation and handling of errors (and how can we access them?)

Thanks! :-)

Was it helpful?

Solution

@1) Normally you add errors via Validation. So your LoginForm should have a validate-method

@2) form.errors() or fomr.error("Field") and form.globalErrors()

@3) At the binding the errors will created and put into the constructor of the form. How ever form.errors().put(key, error) should work, because the Map isn't copied. But this is more a hack and can be changed in the future.

OTHER TIPS

I would suggest form.withError("name", "Error") there is also form.withGlobalError("Error")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top