使用Play 2.3.x我试图了解如何在表单中处理复选框。 This question似乎是旧版Play的过时解决方案。我理解checkbox info will only be posted if checked,但我创建了一个小样本应用,即使我选中了复选框也没有发布信息。这是我的示例“Hello World”应用程序
模型
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;
}
查看
@* 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>
控制器
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)
);
}
}
我想看看我是否可以在调试语句中打印出布尔值true / false信息。现在,即使我点击两个框并提交,它们也会返回null
。此外,我知道复选框有一个视图助手,但我想了解如何使用自定义视图使其工作。 有关如何使用复选框映射布尔属性的任何建议吗?
答案 0 :(得分:7)
想象一下,你有以下几点:
<input type="checkbox" name="box1" checked="checked" value="true"> I have a box1
只要单击(或选中)复选框,名称为box1
的字段就会以true
的形式发送到服务器。如果未选中,则不会为此字段发送任何内容。
我所做的是在模型中设置(在您的情况下,类Hello),布尔字段默认为false:
public Boolean box1=false;
public Boolean box2=false;
在这种情况下,当bindFromRequest()
发生并且POST方法没有为字段box1
和/或box2
发送任何值时,字段将使用默认值填充(错误的。值。
在视图中,您唯一需要的是如下(我不使用播放助手):
<input type="checkbox"
name="@helloForm("box1").name"
value="true"
@if(helloForm("box1").value.contains("true")){checked="checked"}> Box 1
如果该字段已作为true