Sortable & Filterable PrimeFaces DataTable
- by Geertjan
<h:form>
<p:dataTable value="#{resultManagedBean.customers}" var="customer">
<p:column id="nameHeader" filterBy="#{customer.name}" sortBy="#{customer.name}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{customer.name}" />
</p:column>
<p:column id="cityHeader" filterBy="#{customer.city}" sortBy="#{customer.city}">
<f:facet name="header">
<h:outputText value="City" />
</f:facet>
<h:outputText value="#{customer.city}" />
</p:column>
</p:dataTable>
</h:form>
That gives me this:
And here's the filter in action:
Behind this, I have:
import com.mycompany.mavenproject3.entities.Customer;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.RequestScoped;
import javax.inject.Named;
@Named(value = "resultManagedBean")
@RequestScoped
public class ResultManagedBean implements Serializable {
@EJB
private CustomerSessionBean customerSessionBean;
public ResultManagedBean() {
}
private List<Customer> customers;
@PostConstruct
public void init(){
customers = customerSessionBean.getCustomers();
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
And the above refers to the EJB below, which is a standard EJB that I create in all my Java EE 6 demos:
import com.mycompany.mavenproject3.entities.Customer;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class CustomerSessionBean implements Serializable{
@PersistenceContext
EntityManager em;
public List getCustomers() {
return em.createNamedQuery("Customer.findAll").getResultList();
}
}
Only problem is that the columns are only sortable after the first time I use the filter.