我正在使用Play!Framework 2.1.0,以下是解决方案:
1. 在 scala 模板中,您必须给所有复选框名称,如下所示:
@form(action = routes.Application.newPaper()) {
@inputText(paperForm("title"))
@******* Indexed chekbox name *********@
@for((t, index) <- topics.zipWithIndex) {
<input type="checkbox" name="topics[@index]" value="@t">@t <br>
}
<input type="submit" value="Create">
}
2. 然后在您的控制器中,作为处理表单提交的操作,您应该执行以下操作:
public static Result newPaper() {
// Bind submitted form value to your model, ex. Paper.java
Form<Paper> paperForm = Form.form(Paper.class).bindFromRequest();
Paper paper = paperForm.get();
Logger.info("Title entered = " + paper.title);
// Because in template we use indexed name, unchecked item are binded with null value
paper.topics.removeAll(Collections.singleton(null)); // remove value for unchecked topic
for (String t : paper.topics) {
Logger.info("The topic is " + t);
}
Logger.info("Total topic selected = " + paper.topics.size());
return redirect(routes.Application.index()); // redirect page
}
更新
这是解决方案的另一个想法。您在 scala 模板上的复选框代码未修改。
@for(t <- topics) {
<input type='checkbox' name='topic' value=@t>@t <br>
}
所以控制器应该是这样的:
public static Result newPaper() {
// Bind submitted form value to your model, ex. Paper.java
Form<Paper> paperForm = Form.form(Paper.class).bindFromRequest();
Paper paper = paperForm.get();
// get request value from submitted form
Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] checkedVal = map.get("topic"); // get selected topics
// assign checked value to model
paper.topics = Arrays.asList(checkedVal);
// for debugging purpose
for (String t : paper.topics) {
Logger.info("The topic is " + t);
}
Logger.info("Total topic selected = " + paper.topics.size());
return redirect(routes.Application.index()); // redirect page
}
希望这个想法更优雅.. :)
注意:我也在 Play!Framework 2.1.1 上进行了测试,这对我有用。