【发布时间】:2014-09-10 08:01:38
【问题描述】:
我正试图弄清楚如何玩!处理使用多个同名字段的表单。
例如,看看这个表格 sn-p:
<div class="controls" id="orderlines-container">
<div class="orderline form-inline">
<select class="form-control" name="productId[]">
<option disabled selected>Select product...</option>
@for(product<-Product.findAll()) {
<option value="@product.id">@product.name</option>
}
</select>
<input class="form-control" type="number" name="quantity[]" />
<select class="form-control" name="price[]">
<option value="memberPrice" >Member price</option>
<option value="publicPrice" >Public price</option>
</select>
<a href="#" class="btn btn-lg btn-remove"> <span class="glyphicon glyphicon-remove"> </span> </a>
</div>
<a href="#" class="btn btn-success btn-sm" id="btn-add-create"> Add line...</a>
</div>
我使用方括号表示法是因为用户可以通过单击“添加行...”按钮添加任意数量的订单行。单击按钮时,JavaScript 函数会克隆 <div class="orderline"> 并将其附加到下方。所以基本上,提交的表单包含几个订单行。
现在我想做的是收集控制器中的所有数据,但我不知道该怎么做。有人建议我在控制器中做这样的事情:
public static Result createOrder(String[] quantity, String[] productId, String[] price) {
for(int i=0; i<quantity.length; i++){
...
}
for(int i=0; i<productId.length; i++){
...
}
for(int i=0; i<price.length; i++){
...
}
}
但问题在于它需要我为类型Array[String] 实现自定义隐式QueryStringBindable。这样的基本功能是不是太过分了?
所以我的问题是如何处理具有可变数量的同名参数的表单?例如,您将如何实现一个购物车,在其中创建多个订单行(在一个完全随机订单),然后提交创建订单?
PS:我已经尝试使用不同的名称(例如第一行的 [productId0、quantity0、price0],然后是 [productId1、quantity1、price1] 等等。 ..) 对于每个输入,使用 JavaScript,但最终过于复杂而无法保持索引准确...
【问题讨论】:
-
在这里回答类似问题stackoverflow.com/a/10223431/116509
标签: java forms playframework playframework-2.0