emt14
emt14

Reputation: 4896

Why isn't Playframework custom validation message not displayed in template

I am trying to perform some custom validation with play framework but I don't seem to be able to get the error from the template.

The controller code is :


        User user = User.findByEmail(email);

        if(user != null) {
            Logger.warn("User account already created for email %s", email);
            validation.addError("email", "This email address already in use.");
            params.flash();
            flash.error("Please correct the error below!");
            signup();
        }

and the signup.html template:

#{error 'email' /}

I can see that the controller sees the duplicate email but the error message does not appear in the template.

Is the code above correct?

Upvotes: 3

Views: 2356

Answers (1)

Codemwnci
Codemwnci

Reputation: 54944

Because you are going to a different view (i.e. you are redirecting back to the signup view), Play performs a redirect, which means that the errors are no longer in scope, as the signup view is treated as a new request.

To get around this, you need to keep the validation messages available for the next request, which is achieved by using the validation.keep() function.

So, change your code, so that just before you call signup(), you call validation.keep().

Your code should look like

if(user != null) {
    Logger.warn("User account already created for email %s", email);
    validation.addError("email", "This email address already in use.");
    params.flash();
    flash.error("Please correct the error below!");
    validation.keep();
    signup();
}

Upvotes: 6

Related Questions