Is it possible to write a custom filter for a datatable?
I want to filter the data regarding the property status_flag. This status_flag can have following values: available, enable, disabled.
I need a filter method which shows me either the total list or the total list without the disabled.
For Primefaces 5, there is a new attribute filterFunction that makes possible to define custom filter in Java code: http://blog.primefaces.org/?p=3084
However, filter input is still a string in input text.
If you need a custom component to input filter values, or you are stuck with Primefaces 4 (as I am on a recent project), I will describe what worked for me.
I extended filtering behavior using these key steps
filterBy
attributePF('dataTableWidgetVar').filter()
Key thing is to take advantage of filteredValue attribute - when Primefaces filter() function is called or when primefaces filters change, filteredValue is set to list filtered values (or null if no filter applied). Then Primefaces reads filteredValues back from getter to update list of items in dataTable. If we put our filter in between these calls (either in getter or setter, setter is more efficient as it is called only when filters change), we modify original filtered list with our filter and return it back through the getter.
Some code:
Definition of datatable with inputText as filter component:
<p:dataTable filteredValue="#{view.filteredResults} >
...
<p:columnGroup type="header">
...
<p:row>
...
<p:column>
<f:facet name="header">
<p:inputText value="#{view.filterValue}" />
</f:facet>
</p:column>
...
</p:dataTable>
Java Setter and Getter of filteredResults in view named view:
public void setFilteredResults(List<?> filteredResults) {
this.filteredResults = applyPremiumFilters(filteredResults, filterValue);
}
public List<?> getFilteredResults() {
return this.filteredResults;
}
The rest is Javascript code to apply filter on dataTable when value in filter component is changed.
Of course you can,
I will give you an example below:
<p:column filterBy="status"
filterOptions="#{yourBean.statusOptions}"
filterMatchMode="exact">
...
</p:column>
The Java code:
public List<SelectItem> getStatusOptions()
{
List<SelectItem> options = new ArrayList<SelectItem>();
options.add(new SelectItem("avalaible", "Avalaible"));
options.add(new SelectItem("enable", "Enable"));
options.add(new SelectItem("disabled", "Disabled"));
return options;
}
Using SelectItem.
You will find an example here http://www.primefaces.org/showcase/ui/datatableFiltering.jsf
Hope it will help...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With