Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to define optional parameter when rendering an scala template 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 looks like this:

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

Also tried:

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

In both cases i got "error: method render in class recover cannot be applied to given types;"

like image 741
joafeldmann Avatar asked Aug 07 '12 10:08

joafeldmann


1 Answers

From Java controller you can't omit assignation of the value (in Scala controller or other template it will work), the fastest and cleanest solution in this situation is assignation every time with default value, ie:

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 template can stay unchanged, as Scala controllers and other templates which can call the template will respect the default value if not given there.

BTW: as you can see, you should use proper methods for returning results from Play's actions, see ok() vs badRequest() also: forrbiden(), notFound(), etc, etc

You can also use flash scope for populating messages and use redirect() to main page after successful password change, then you can just check if flash message exists 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 snippet is copied from Computer Database sample for Java, so you can check it on your own disk)

like image 171
biesior Avatar answered Oct 16 '22 21:10

biesior