Tuesday, May 12, 2009

Spring bind collection to checkbox

Here is an example in JSP to bind a collection as checkboxes with spring form:checkbox.

<c:forEach varStatus="status" var="product" items="${command.products}">
<form:checkbox path="products[${status.index}].productId" value="${product.id}" />
</c:foreach>

Note the command will always have the collection "products". However, the selected ones - the ones with checkbox checked, will have valid "id" values. This is the way to tell which ones are selected.

1 comment:

  1. Thanks
    For me I had to override equals and hashCode methods too.

    @Override
    public int hashCode() {

    return new Long(productId).hashCode()*description.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
    // TODO Auto-generated method stub
    if (obj == null) {
    return false;
    }
    if (! (obj instanceof Product)) {
    return false;
    }
    return this.productId==((Product)obj).getproductId();
    }

    ReplyDelete