vendredi 24 avril 2015

Play Framework submitting boolean values with checkbox?

Using Play 2.3.x I am trying to understand how checkboxes are handled in forms. This question seems like a solution for an older version of Play. I understand that checkbox info will only be posted if checked, but I've created a small sample app and no info is posted even if I check the boxes. Here is my sample "Hello World" application

Model

public static class Hello {
    @Required public String name;
    @Required @Min(1) @Max(100) public Integer repeat;
    public String color;
    public Boolean box1;
    public Boolean box2;
}

View

    @* For brevity, here is the checkbox code *@
    <label>
        <input type="checkbox"
         name="@helloForm("box1").name"
         value="@helloForm("box1").value"> Box 1
    </label>
    <label>
        <input type="checkbox"
         name="@helloForm("box2").name"
         value="@helloForm("box2").value"> Box 2
    </label>

Controller

public static Result sayHello() {
    Form<Hello> form = Form.form(Hello.class).bindFromRequest();
    if(form.hasErrors()) {
        return badRequest(index.render(form));
    } else {
        Hello data = form.get();
        Logger.debug("Box 1 was " + data.box1);
        Logger.debug("Box 2 was " + data.box2);
        return ok(
                hello.render(data.name, data.repeat, data.color)
        );
    }
}

I want to see if I can get the boolean true/false information printed in the debug statements. Right now even if I click both boxes and submit, they return as null. Also, I know that there is a view helper for checkboxes, but I want to understand how to get this working using a custom view. Any advice on how to use checkboxes to map Boolean attributes?

PS - full code is here if you'd like to try it




Aucun commentaire:

Enregistrer un commentaire