Play Framework sends boolean values ​​using a checkbox?

Using Play 2.3.x I am trying to understand how checkboxes are handled in forms. This question seems to be an outdated solution for an older version of Play. I understand that the checkbox will only be checked if the checkbox is checked , but I created a small example app and no information was sent even if I check the checkboxes. Here is a 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 boolean true / false information printed in debug operations. Right now, even if I hit both fields and submit, they return as null

. Also, I know there is a checkbox reference for checkboxes, but I want to understand how to get this to work using a custom view. Any advice on how to use checkboxes to map boolean attributes?

PS - full code here if you want to try

+3


source to share


1 answer


Imagine you have the following:

<input type="checkbox" name="box1" checked="checked" value="true"> I have a box1

      

The name field box1

will be sent to the server true

just like whenever the checkbox is checked (or checked). If this check box is not selected, nothing will be sent for this field.

What I am doing is to set in the model (in your case the Hello class) the boolean field is by default false:

public Boolean box1=false;
public Boolean box2=false;

      



In this case, when it happens bindFromRequest()

and the POST method has not sent any value for the field box1

and / or box2

, the fields will be filled with a default value (false).

In the view, the only thing you will need is the following (I'm not using the playhead helper):

<input type="checkbox"
     name="@helloForm("box1").name"
     value="true" 
     @if(helloForm("box1").value.contains("true")){checked="checked"}> Box 1

      

This will check your checkbox if the field was sent to view as true

+7


source







All Articles