Play 2 - How to set default template parameter value from Java controller?

Can I define an optional parameter when rendering a scala template in Play Framework 2?

My controller is as follows:

public static Result recoverPassword() { Form<RecoveryForm> resetForm = form(RecoveryForm.class); return ok(recover.render(resetForm)); // On success I'd like to pass an optional parameter: // return ok(recover.render(resetForm, true)); } 

My scala template is as follows:

 @(resetForm: Form[controllers.Account.RecoveryForm], success:Boolean = false) 

Also tried:

 @(resetForm: Form[controllers.Account.RecoveryForm]) (success:Boolean = false) 

In both cases, I got an "error: the rendering method in the recovery class cannot be applied to the given types";

+7
source share
1 answer

From the Java controller, you cannot omit the value assignment (it will work in the Scala controller or another template), the fastest and cleanest solution in this situation is to assign the default value each time, that is:

 public static Result recoverPassword() { Form<RecoveryForm> resetForm = form(RecoveryForm.class); if (!successfullPaswordChange){ return badRequest(recover.render(resetForm, false)); } return ok(recover.render(resetForm, true)); } 

The Scala pattern may remain unchanged, because Scala controllers and other patterns that can invoke the pattern will respect the default if not specified.

BTW: as you can see, you should use the correct methods to return the results from the Play actions , see ok() vs badRequest() also: forrbiden() , notFound() , etc. etc.

You can also use the flash area to fill in messages and use redirect() on the main page after successfully changing the password, then you can simply check if the flash message exists and displays it:

 public static Result recoverPassword() { ... if (!successfullPaswordChange){ return badRequest(recover.render(resetForm, false)); } flash("passchange.succces", "Your password was reseted, check your mail"); return redirect(routes.Application.index()); } 

in ANY template:

 @if(flash.containsKey("passchange.succces")) { <div class="alert-message warning"> <strong>Done!</strong> @flash.get("passchange.succces") </div> } 

(this snippet is copied from a sample Java computer database, so you can check it on your own disk)

+6
source

All Articles