Dynamically binding lists with Spring's form tag
Asked Answered
A

1

10

I have a command object FaxForm and it holds a list of FaxStatus objects inside a faxStatusList property.

public class FaxForm {
  private List<FaxStatus> faxStatusList;
  public void setFaxStatusList(List<FaxStatus> faxStatusList) {
    this.faxStatusList = faxStatusList;
  }
  public List<FaxStatus> getFaxStatusList() {
    return faxStatusList;
  }
}

I initially had a JSP page that would bind the objects by performing the following:

<c:forEach items="${esaFaxForm.faxStatusList}" var="item" varStatus="loop">
  <tr class="tableAltBackground">
    <td>
      <form:checkbox path="faxStatusList[${loop.index}].selected"/>
    </td>
    <td>
      <form:select path="faxStatusList[${loop.index}].status" items="${esaFaxForm.statusOptions}" onchange="checkThisBox(this);"/>
    </td>
    <td>
      <a href="${statusContUrl}?id=${item.id}&status=${item.status}" onclick="openFaxWindow('${viewFaxUrl}?id=${item.id}', ${loop.index});">${item.name}</a>
      <form:hidden path="faxStatusList[${loop.index}].name"/>
    </td>
    <td>
      <a href="${statusContUrl}?id=${item.id}&status=${item.status}" onclick="openFaxWindow('${viewFaxUrl}?id=${item.id}', ${loop.index});">${item.id}</a>
      <form:hidden path="faxStatusList[${loop.index}].id"/>
    </td>
  </tr>
</c:forEach>

However, I am trying to figure out how I could do the binding without the forEach loop and index. The examples on the Spring website show the binding by setting the path to the list name. Is there a way to bind the properties? I've tried this but it fails:

<form:checkbox path="faxStatusList.faxStatus.selected"/>
<form:select path="faxStatusList.faxStatus.status" items="${esaFaxForm.statusOptions}"/>

The faxStatusList has a getter and setter method and the FaxStatus variables each have getter/setter properties. I get the error "Invalid property 'faxStatusList.faxStatus' of bean class..."

Aric answered 19/12, 2009 at 21:3 Comment(2)
faxStatusList is a indexed property. So you can not use something like faxStatusList.faxStatus. Use faxStatusList[<CURRENT_INDEX>].faxStatus instead.Shepp
I actually like your current code as an answer, as it offers a great deal of flexibility.Carter
G
9

Spring form tags has a checkboxes tag. You can use it as follows to do the binding automatically:

<form:checkboxes items="${faxStatusList}" path="faxStatusList" itemLabel="name" itemValue="id" delimiter="<br/>" onclick="yourOnClickMethodIfYouNeed(this);"/>

The above snippet will display a list of checkbox items delimited with the br tag. Any changes made to the state of the checkboxes will be reflected appropriately in your FaxForm. faxStatusList object.

Galagalactagogue answered 21/12, 2009 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.