Saturday, February 21, 2009

Struts2 nested checkbox tag inside iterator

Using the s:iterator tag and status attribute it's possible to display and update values of complex types within a collection.

For example, using an iterator tag,

<s:iterator value="results" status="status">

<s:hidden value="%{product.sku}" name="results[%{#status.index}].product.sku" />

<input type="checkbox" name="results[<s:property value="%{#status.index}" />].selected" <s:property value="%{selected}" />>

</s:iterator>

within a form tag, the submit action will update the list of results in the Action class, where my action class has

protected List<ProductBean> results;

with getters and setters, and my ProductBean has,

private Product product;

with getters and setters, and

private boolean selected;

/**
* @return the selected
*/
public String isSelected() {
    return selected ? "checked" : "";
}

/**
* @param selected the selected to set
*/
public void setSelected(String selected) {
    this.selected = selected == null || selected.equals("") ? false : true;
}

Note: If you find something useful, please leave a comment, thanks!

No comments: