gpt4 book ai didi

java - Play Framework 2.0 表单助手 : from checkbox to List

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:59 26 4
gpt4 key购买 nike

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

public String title;    
public List<String> topics;

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

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

使用简单的字符串,效果很好。但我想显示复选框

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

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

最佳答案

我正在使用 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。然后在你的 Controller 中,作为处理表单提交的 Action ,你应该做这样的事情:

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>
}

所以 Controller 应该是这样的:

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 上进行了测试,这对我来说很管用。

关于java - Play Framework 2.0 表单助手 : from checkbox to List<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11562292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com