[英]Dynamic size of form in Play framework 2.7 (Java)
我想使用 Java 中的Play 框架 2.7创建一个表单应用程序,我想创建表单的所有字段一定次数,在创建之前我不知道。
这是我的模型之一:
public class Information {
public String clientType;
public String companyName;
public String name;
public String firstName;
public String addressNumber;
public String apartmentType;
public Information(String companyName, String name, String firstName, String addressNumber, String clientType,
String apartmentType) {
this.clientType = clientType;
this.companyName = companyName;
this.name = name;
this.firstName = firstName;
this.addressNumber = addressNumber;
this.apartmentType = apartmentType;
}
}
在这里,我的表单数据之一:
public class InformationData {
@Constraints.Required
private String clientType;
@Constraints.Required
private String companyName;
@Constraints.Required
private String name;
@Constraints.Required
private String firstName;
@Constraints.Required
private String addressNumber;
@Constraints.Required
private String apartmentType;
public InformationData() {
}
// getters and setters
}
在这里,我的一部分观点:
@(informationForm: play.data.Form[data.InformationData])
<h1>Informations</h1>
@helper.form(routes.InformationController.validationInformations) {
@helper.CSRF.formField
@helper.inputText(
informationForm("fieldName"),
Symbol("_help") -> "",
Symbol("_error") -> informationForm("fieldName").
error.map(_.withMessage("ERROR"))
)
<button type="submit">Submit</button>
}
在我的控制器中,我有这个属性private final Form<InformationData> form;
它将用作我的视图的参数( Twirl模板)。
我尝试将此属性转换为java.util.List
并在我看来在此 List 上使用@for
循环(在我看来它变成了 Scala Seq)但表单的验证不正确:它考虑了每个(对于示例) name
字段作为相同的字段,因此在验证期间它只会用第一个字段的值填充每个name
字段的值(即使第一个为空而另一个不是)。
编辑
我试图用循环的当前索引修改我所有字段的名称(即: name0
然后name1
等等),它停止了我的字段的混乱,因为它们没有相同的名称,但我的InformationData
不能验证,因为它无法识别我的字段的名称。
是否有可能通过使用 HashMap 或其他东西来理解name0
和name1
应该被视为(不同的) name
?
如果您需要信息列表,只需构建包含信息列表的表单,如下所示:
public class InformationData {
@Constraints.Required
private List<Information> informations;
// setter and getter
}
在您的网页中,您可以像这样使用列表:
@(informationForm: play.data.Form[InformationData])
//your html
@for(information<-informationForm.get().getInformations()){
<p>@information.getName</p>
<p>@information.getCompanyName</p>
//all your stuff to print
}
//your html
请记住,要检索字段,您应该先“get()”表单,然后才能访问其中的方法。
informationForm.get().getInformations()
要检查列表的长度,只需调用“length”方法。
informationForm.get().getInformations.length
对于表单部分,要在 html 中构建,您必须提供一个有效的名称来构建一个值列表,例如
@helper.form(routes.InformationController.validationInformations) {
@helper.CSRF.formField
<input type="text" name="name[0]" value="">
<input type="text" name="companyName[0]" value="">
.....
<input type="text" name="name[N]" value="">
<input type="text" name="companyName[N]" value="">
<button type="submit">Submit</button>
}
如果你不能事先用 Scala 打印它,你应该用一些 javascript 动态创建你的输入字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.