Sortable & Filterable PrimeFaces DataTable

Posted by Geertjan on Oracle Blogs See other posts from Oracle Blogs or by Geertjan
Published on Tue, 30 Oct 2012 22:09:22 +0000 Indexed on 2012/10/30 23:11 UTC
Read the original article Hit count: 265

Filed under:
<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.

© Oracle Blogs or respective owner

Related posts about /NetBeans IDE