jsfprimefacesdatatable

Filter p:datatable by boolean column (checkbox)


I am trying to filter my primefaces datatable by a boolean column using a checkbox filter but unfortunately filtering in primefaces datatable seems it does not work with any type other than String, but there should be a workaround for this case.

datatable column

<p:column headerText="A_boolean_column" filterBy="#{myBean.myBoolean}"  filterMatchMode="exact">
  <f:facet name="filter">
     <p:selectCheckboxMenu label="BooleanFilter" onchange="PF('mydatatable').filter()" styleClass="custom-filter">
       <f:selectItems value="#{myBean.possibleAnswers}" />
       <p:ajax update="@form" oncomplete="PF('mydatatable').filter();"/>
    </p:selectCheckboxMenu>
  </f:facet>
     <h:outputText value="#{myBean.myBoolean}"/>
</p:column>

where possibleAnswers variable is a list that has been initialized on init method of myBean with true && false values

      @PostConstruct
      public void init(){
        this.possibleAnswers= new ArrayList<>();
        possibleAnswers.add(true);
        possibleAnswers.add(false);
      }

I have similar working examples in my datatable with text values and are working perfectly. Of course I could do a workaround to fix my issue by converting the values from boolean ( true / false) into String ("true" / "false") ( or even write a custom function to check for equality)but I don't really like this solution and I would prefer any other out of the box solution ( perhaps a different filterMatchMode ? ).

I am using primefaces 7.0


Solution

  • Normally an input component has a 'value' attribute that is bound to a field (getter/setter) in a backing bean. The type of this field can be used to automatically convert the technical string of the http request to the correct java type. For a datatable filter this cannot be automatically done since there is no value attribute. Giving all components knowledge about all possible containers they can be used in is bad design. So the only and corrrect solution is to use an explicit converter.

    Have a Look at the Implementation of the Status-Column in the PrimeFaces datatable filter showcase, as far as I see it it is exactly what you need

    for Reference:

    <p:column filterBy="#{myBean.myBoolean}" filterMatchMode="in">
       <f:facet name="filter"> 
          <p:selectCheckboxMenu label="BooleanFilter" 
             onchange="PF('mydatatable').filter()" styleClass="custom-filter"> 
             <f:converter converterId="javax.faces.Boolean" /> 
             <f:selectItems value="#{myBean.possibleAnswers}" /> 
             <p:ajax update="@form" oncomplete="PF('mydatatable').filter();"/> 
          </p:selectCheckboxMenu> 
       </f:facet> 
    </p:column>