jsfprimefacesprimefaces-datatable

PrimeFaces DataTable rowSelect cannot check checkbox


I was trying to "link" <p:ajax event="rowSelect"> and <p:ajax event="rowUnselect"> with <h:selectBooleanCheckbox> so when datatable row is selected, the checkbox would check together and when checkbox is checked, datatable row is selected too.

Problem for now: I can save the state of the checkbox when going to another pagination page but I need to check checkbox then select row then only it will save the state. If I tried to check only checkbox and go to other pagination page, it won't save the state when I come back to the pagination page but if I select row and go to other pagination page, it would save the state. If I select row and check checkbox and go to another pagination page, it won't save the state too. Any idea how to check checkbox and select row when either 1 is clicked and can save state if go to another pagination page?

    <p:dataTable value="#{machine.sub}" var="subDir" 
                 id="fileDirectories" rowClasses="row1-whitebg,row2-bluebg" 
                 selectionMode="multiple" selectionPageOnly="false" 
                 rowKey="#{subDir.directory.path}" headerClass="title-column" 
                 rowIndexVar="idx" rows="10" rowsPerPageTemplate="10,20,50" paginator="true" 
                 paginatorAlwaysVisible="false" 
                 paginatorTemplate="#{WebConstant.PAGINATOR_TEMPLATE}">
    
                <p:ajax event="rowSelect" listener="#{machine.selectedRow}"/>
                <p:ajax event="rowUnselect" listener="#{machine.unSelectedRow}"/>
        
                <p:column>
                    <f:facet name="header">
                        <h:outputText value="#{msg['machine_download']}"/>
                    </f:facet>
                    <h:panelGroup id="panelGroupChkSelect">
                        <h:selectBooleanCheckbox id="chkSelect" value="#{subDir.selected}"
                                                 rendered="#{subDir.directory.file}">
                            <c:if test="#{machineLogExplorerPage.checkButton()}">
                                <f:attribute name="checked" value="checked"/>
                            </c:if>
                        </h:selectBooleanCheckbox>
                    </h:panelGroup>
                </p:column>
    </p:dataTable>

Java code

private boolean checked;

  public void selectedRow() {
    checked = true;
  }

  public void unSelectedRow() {
    checked = false;
  }

  public boolean checkButton() {
    return checked;
  }

Solution

  • You don't need to implement the checkbox yourself. Just add a selection column like:

    <p:column selectionMode="multiple"/>
    

    To keep track of what is selected use:

    <p:dataTable selectionMode="multiple"
                 selection="#{bean.listOfSelectedItems}"
                 ...>
    

    See: