Play Framework 2.0表单助手:从复选框到List <string> </string>

时间:2012-07-19 13:48:31

标签: java forms playframework playframework-2.0

我有一个包含字符串和列表的模型:

public String title;    
public List<String> topics;

在index.scala.html中,我使用表单添加新项目:

@form(routes.Application.newPaper()) {
    @inputText(paperForm("title"))
    <input type="submit" value="Create">
    }

使用简单的String,这很好用。但我想显示复选框

@for(t <- topics) {
    <input type='checkbox' name='topic' value=@t>@t <br>
}

然后将所有选中的“主题”添加到我的新项目的List<String> topics;。如何处理@form {...}中的复选框?

1 个答案:

答案 0 :(得分:16)

我正在使用 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上测试过,这对我有用。