KJ50 KJ50 - 2 months ago 8
Javascript Question

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 an outdated 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

Answer

Imagine you have the following:

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

The field with name box1 will be sent to the server as true whenever the checkbox is clicked (or checked). When is not checked, nothing will be sent for this field.

What I do is to set in the model (in your case, the class Hello),the Boolean field by default to false:

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

In this case, when the bindFromRequest() occurs and the POST method did not send any value for the field box1 and/or box2, the fields will be filled with the default (false) value.

On the view, the only thing you will need, is as follows (I don't use the play 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 the view as true

Comments