KJ5*_*J50 3 javascript forms checkbox playframework playframework-2.3
使用Play 2.3.x我试图理解如何在表单中处理复选框.这个问题似乎是旧版Play的过时解决方案.我知道只有选中后才会发布复选框信息,但是我创建了一个小样本应用程序,即使我选中了复选框也没有发布信息.这是我的示例"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;
}
Run Code Online (Sandbox Code Playgroud)
视图
@* 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>
Run Code Online (Sandbox Code Playgroud)
调节器
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)
);
}
}
Run Code Online (Sandbox Code Playgroud)
我想看看我是否可以获得调试语句中打印的布尔值true/false信息.现在,即使我点击两个框并提交,它们也会返回null.此外,我知道复选框有一个视图助手,但我想了解如何使用自定义视图使其工作.关于如何使用复选框来映射布尔属性的任何建议?
PS - 完整代码在这里,如果你想尝试它
想象一下,你有以下几点:
<input type="checkbox" name="box1" checked="checked" value="true"> I have a box1
Run Code Online (Sandbox Code Playgroud)
只要单击(或选中)复选框box1,true就会将带有名称的字段发送到服务器.如果未选中,则不会为此字段发送任何内容.
我所做的是在模型中设置(在您的情况下,类Hello),布尔字段默认为false:
public Boolean box1=false;
public Boolean box2=false;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,当bindFromRequest()发生并且POST方法没有为字段发送任何值box1和/或时box2,字段将填充默认(false)值.
在视图中,您唯一需要的是如下(我不使用播放助手):
<input type="checkbox"
name="@helloForm("box1").name"
value="true"
@if(helloForm("box1").value.contains("true")){checked="checked"}> Box 1
Run Code Online (Sandbox Code Playgroud)
如果该字段已发送到视图,则会检查您的复选框 true
| 归档时间: |
|
| 查看次数: |
5429 次 |
| 最近记录: |