Search code examples
javascriptcheckboxstruts2struts-tags

How to display preselected checkboxes in a Struts2 Iterator


I'm displaying a list as checkboxes. In this some checkboxes should be prechecked based on the database values. If I use checkboxlist I can achive this, but I'm able to display only one property(listValue) after checkbox. I need to display more than one property after checkbox.

<s:checkboxlist list="myList" name="checkboxes" listKey="id" listValue="name" value="selectedList"/>

here myList has the available checkboxes and selectedList contain the keys that should be precheked

So how to achieve the same functionality with a checkbox in an iterator...? The code that I have tried to display available checkboxes are...

<s:iterator value="myList" var="record">
  <s:checkbox name="id" value="%{#record.id}"/>
  <s:property value="#record.name"/>
  <s:property value="#record.description"/>
</s:iterator> 

Solution

  • Using <s:checkboxlist> tag you can simply concatenate properties in listValue attribute.

    <s:checkboxlist list="myList" 
                    name="checkboxes" 
                    listKey="id" 
                    listValue="name +' '+ description" 
                    value="selectedList" />
    

    If you prefer to iterate over list by yourself use list's contains method to set some checkboxes as checked.

    Note that value attribute of <s:checkbox> tag is for setting if checkbox will be checked or not. To set value which will be sent to server you need to use fieldValue attribute.

    <s:iterator value="records" var="record">
        <label>
            <s:checkbox name="id" 
                        fieldValue="%{#record.id}" 
                        value="selectedList.contains(#record.id)" />
    
            <s:property value="#record.name" />
            <s:property value="#record.description" />
        </label>
    </s:iterator>
    

    Don't forget about labels, by using them you can check checkboxes by clicking on label text.