我想知道的是,在使用SpringMVC和Spring forms时,是否有更简单/更好的方法来处理动态表单(通过js将表单项添加到dom中)?
具有具有多个LineItems的发票对象的图像。
public class Invocie {
private List LineItems;
public Invoice() {
lineItems = ListUtils.lazyList(new ArrayList<LineItem>(), FactoryUtils.instantiateFactory(LineItem.class));
}
}
显示属于我当前使用的发票的项目
<forEach items="${invoice.lineItems}" varStatus="i">
<form:input path="lineItems[${i.index}].productName" />
</c:forEach>
为了添加LineItems,我使用一些js来计算新的索引并将其添加到DOM中。当删除一个LineItem时,我目前不得不重新编号所有的索引,这是我想要避免的部分,这是可能的吗?
发布于 2009-06-23 08:40:39
您可以使用以下代码
public class InvoiceController extends SimpleFormController {
protected void initBinder(HttpServletRequest request, ServletRequetDataBinder binder) throws Exception {
binder.registerCustomEditor(List.class, "lineItems", new CustomCollectionEditor(List.class)() {
protected Object convertElement(Object lineItem) {
LineItem li = (LineItem) lineItem;
// StringUtils is a jakarta Commons lang static class
return (StringUtils.isBlank(li.getProductName())) ? null : li;
}
});
}
}
然后在onBind方法中,根据以下内容删除空引用:
protected void onBind(HttpServletRequest request, Object command, BindException bindException) throws Exception {
Invoice invoice = (Invoice) command;
invoice.getLineItems().removeAll(Collections.singletonList(null));
}
致以敬意,
发布于 2009-07-14 00:05:45
我发现,为了避免在GrowthList中添加/设置项时出现一些错误,还需要使用JSP来进行装饰。(还创建了一个自定义的SpringList实现。这基本上完成了双重装饰。)
lineItems = GrowthList.decorate(ListUtils.lazyList(new ArrayList<LineItem>(), FactoryUtils.instantiateFactory(LineItem.class)));
我同意。问题当然是删除项目。
您可以做的是在html中使用spring marker语法。因此,如果您使用javascript从列表中删除一个项目(例如,在索引2处),则可以使用以下命令标记该索引:
<input type="hidden" name="_lineItems[2]">
然后,当表单提交时,spring将看到该标记,并为lineItems2放入一个空项目(基于lazylist工厂),而不是忽略它。
发布于 2010-12-30 03:57:28
我今天一直在努力解决这个问题,并想出了一些描述here的解决方案。
https://stackoverflow.com/questions/890250
复制相似问题