Play 2 – how do I set the default values of template parameters from the Java controller?
Can I define optional parameters when rendering Scala templates in play framework 2?
My controller looks like this:
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 get "error: Method rendering in class recovery cannot be applied to a given type;"
Solution
From the Java controller, you cannot omit the value assignment (it will work in the scala controller or other templates). In this case, the fastest and cleanest solution is to use the default value every 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)); }
Scala templates can remain unchanged because Scala controllers and other templates that can invoke templates will follow the default values (if not given there)
By the way: as you can see, you should use appropriate methods to return results from play actions. See OK () vs badrequest (): forrbiden (), notfound (), and so on
You can also use flash scope to fill in the mail and use redirect() to the home page after the password is successfully changed. Then you can check whether there is a flash message and display 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 fragment is copied from the computer database example in Java, so you can check it on your own disk)