5/15/2012

Multiple checkboxes writing into one variable, in a repeat control

This time a very special control: you want to include checkboxes in a repeat control or a view control for every row that is rendered.
This should work for pager etc. and write into one single variable. Usually this does not work, as a CheckboxGroup cannot span over other tags.
I found the following workaround, that uses a HashMap in the sessionScope to store the values. Unfortunately, this only seems to work with regular updates, as the pager control does not save values for already checked boxes.

If you got any better idea, please let me know.

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
    <xp:checkBox text="#{javascript:compositeData.text;}"
        checkedValue="#{javascript:compositeData.checkedValue;}" immediate="true"
        id="checkBox1">
        <xp:this.defaultChecked><![CDATA[#{javascript:
            var result = sessionScope.get(compositeData.variableName);
            if(result==null){
                return false;
            }
            else{
                return result.get(''+compositeData.variableIndex)!=null;
            }
            }]]>
        </xp:this.defaultChecked>
        <xp:eventHandler event="onclick" submit="true"
            refreshMode="norefresh">
            <xp:this.action><![CDATA[#{javascript:
                if(sessionScope.get(compositeData.variableName)==null){
                    sessionScope.put(compositeData.variableName,new java.util.HashMap());
                }
                sessionScope.get(compositeData.variableName).put(''+compositeData.variableIndex,this.parent.value);}]]>
            </xp:this.action>
        </xp:eventHandler>
    </xp:checkBox>
</xp:view>



Example usage:

<xp:pager layout="Previous Group Next" id="pager1" for="repeat1"
    partialRefresh="true">
</xp:pager>
<xp:table style="width:100.0%">
<xp:repeat id="repeat1" rows="10" var="customer" indexVar="customerIndex">
    <xp:this.value><![CDATA[#{javascript:sessionScope.customerData;}]]></xp:this.value>

    <xp:tr>
        <xp:td>
            <xc:checkBoxWithGroup checkedValue="#{javascript:customer.id;}"
             text="#{javascript:customer.name;}" variableName="selectedCustomers"
             variableIndex="#{javascript:customerIndex;}" >
            </xc:checkBoxWithGroup>
        </xp:td>
    </xp:tr>
</xp:repeat>
</xp:table>