MultiViewState (MVS) feature enables DataTable to maintain its state across pages by setting multiViewState attribute to true. In this demo, manipulate DataTable with pagination, sorting, filtering and selection, then visit another page and then come back to this page. DataTable state should remain as you've left it.
<style>
.ui-datatable .ui-datatable-header {
text-align: right !important;
}
.ui-selectcheckboxmenu-panel .ui-selectcheckboxmenu-header .ui-chkbox {
display: none;
}
</style>
<h:form id="form">
<p:messages id="messages"/>
<div class="card">
<h5>Basic</h5>
<p:dataTable id="tableStateDT" var="customer" value="#{dtMultiViewStateView.customers}"
widgetVar="customersTable" multiViewState="true" rows="10" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" selectionMode="single"
selection="#{dtMultiViewStateView.selectedCustomer}" rowKey="#{customer.id}"
emptyMessage="No customers found with given criteria"
filteredValue="#{dtMultiViewStateView.filteredCustomers}">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search all fields:"/>
<p:inputText id="globalFilter" onkeyup="PF('customersTable').filter()" style="width:150px"
placeholder="Enter keyword"/>
</p:outputPanel>
</f:facet>
<p:ajax event="rowSelect" update=":form:customerDetail" oncomplete="PF('customerDialog').show()"/>
<p:column headerText="Name" filterBy="#{customer.name}" sortBy="#{customer.name}"
filterMatchMode="contains">
<h:outputText value="#{customer.name}"/>
</p:column>
<p:column headerText="Country" filterBy="#{customer.country.name}" sortBy="#{customer.country.name}"
filterMatchMode="startsWith">
<span class="flag flag-#{customer.country.code}" style="width: 30px; height: 20px"/>
<h:outputText style="vertical-align: middle; margin-left: .5rem"
value="#{customer.country.name}"/>
</p:column>
<p:column headerText="Representative" filterBy="#{customer.representative.name}"
sortBy="#{customer.representative.name}" filterMatchMode="startsWith">
<p:graphicImage name="images/avatar/#{customer.representative.image}" library="demo"
width="32" style="vertical-align: middle"/>
<h:outputText style="vertical-align: middle; margin-left: .5rem"
value="#{customer.representative.name}"/>
</p:column>
<p:column headerText="Status" filterBy="#{customer.status}" sortBy="#{customer.status}"
filterMatchMode="exact">
<f:facet name="filter">
<p:selectOneMenu onchange="PF('customersTable').filter()"
style="width:100%; box-sizing: border-box;">
<f:selectItem itemLabel="Select One" itemValue="#{null}" noSelectionOption="true"/>
<f:selectItems value="#{dtMultiViewStateView.customerStatus}"/>
</p:selectOneMenu>
</f:facet>
<span class="customer-badge status-#{customer.status.name().toLowerCase()}">#{customer.status}</span>
</p:column>
<f:facet name="paginatorTopLeft">
<p:commandButton value="Clear table state" action="#{dtMultiViewStateView.clearMultiViewState}"
update="@form"/>
</f:facet>
</p:dataTable>
</div>
<br/>
<div class="card">
<h5>Lazy Loading</h5>
<p:dataTable var="customer" value="#{dtLazyView.lazyModel}" paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="customerTable" multiViewState="true">
<p:column headerText="Name" sortBy="#{customer.name}" filterBy="#{customer.name}">
<h:outputText value="#{customer.name}"/>
</p:column>
<p:column headerText="Country" sortBy="#{customer.country}" filterBy="#{customer.country}">
<span class="flag flag-#{customer.country.code}" style="width: 30px; height: 20px"/>
<h:outputText style="vertical-align: middle; margin-left: .5rem" value="#{customer.country}"/>
</p:column>
<p:column headerText="Representative" sortBy="#{customer.representative}"
filterBy="#{customer.representative}" filterMatchMode="startsWith">
<p:graphicImage name="images/avatar/#{customer.representative.image}" library="demo"
width="32" style="vertical-align: middle"/>
<h:outputText style="vertical-align: middle; margin-left: .5rem"
value="#{customer.representative.name}"/>
</p:column>
<p:column headerText="Status" sortBy="#{customer.status}" filterBy="#{customer.status}">
<span class="customer-badge status-#{customer.status.name().toLowerCase()}">#{customer.status}</span>
</p:column>
<f:facet name="paginatorTopLeft">
<p:commandButton value="Clear table state" action="#{dtMultiViewStateView.clearMultiViewState}"
update="@form"/>
</f:facet>
</p:dataTable>
</div>
<p:dialog header="Customer Info" widgetVar="customerDialog" modal="true" showEffect="fade" hideEffect="fade"
resizable="false">
<p:outputPanel id="customerDetail" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty dtMultiViewStateView.selectedCustomer}"
columnClasses="label,value">
<h:outputText value="Name:"/>
<h:outputText value="#{dtMultiViewStateView.selectedCustomer.name}"/>
<h:outputText value="Country"/>
<p:column>
<span class="flag flag-#{dtMultiViewStateView.selectedCustomer.country.code}"
style="width: 30px; height: 20px"/>
<h:outputText style="vertical-align: middle; margin-left: .5rem"
value="#{dtMultiViewStateView.selectedCustomer.name}"/>
</p:column>
<h:outputText value="Representative"/>
<p:column>
<p:graphicImage
name="images/avatar/#{dtMultiViewStateView.selectedCustomer.representative.image}"
library="demo"
width="32" style="vertical-align: middle"/>
<h:outputText style="vertical-align: middle; margin-left: .5rem"
value="#{dtMultiViewStateView.selectedCustomer.representative}"/>
</p:column>
<h:outputText value="Status:"/>
<span class="customer-badge status-#{dtMultiViewStateView.selectedCustomer.status.name().toLowerCase()}">#{dtMultiViewStateView.selectedCustomer.status}</span>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
@Named("dtMultiViewStateView")
@ViewScoped
public class MultiViewStateView implements Serializable {
private List<Customer> customers;
private List<Customer> filteredCustomers;
private Customer selectedCustomer;
@Inject
private CustomerService service;
@PostConstruct
public void init() {
customers = service.getCustomers(50);
}
public List<Customer> getCustomers() {
return customers;
}
public List<Customer> getFilteredCustomers() {
return filteredCustomers;
}
public Customer getSelectedCustomer() {
return selectedCustomer;
}
public CustomerStatus[] getCustomerStatus() {
return CustomerStatus.values();
}
public void setSelectedCustomer(Customer selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public void setFilteredCustomers(List<Customer> filteredCustomers) {
this.filteredCustomers = filteredCustomers;
}
public void setService(CustomerService service) {
this.service = service;
}
public void clearMultiViewState() {
FacesContext context = FacesContext.getCurrentInstance();
String viewId = context.getViewRoot().getViewId();
PrimeFaces.current().multiViewState().clearAll(viewId, true, this::showMessage);
}
private void showMessage(String clientId) {
FacesContext.getCurrentInstance()
.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, clientId + " multiview state has been cleared out", null));
}
}
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String company;
private Country country;
private LocalDate date;
private CustomerStatus status;
private int activity;
private Representative representative;
public Customer() {
}
public Customer(int id, String name, String company, Country country, LocalDate date, CustomerStatus status, int activity,
Representative representative) {
this.id = id;
this.name = name;
this.company = company;
this.country = country;
this.date = date;
this.status = status;
this.activity = activity;
this.representative = representative;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public CustomerStatus getStatus() {
return status;
}
public void setStatus(CustomerStatus status) {
this.status = status;
}
public int getActivity() {
return activity;
}
public void setActivity(int activity) {
this.activity = activity;
}
public Representative getRepresentative() {
return representative;
}
public void setRepresentative(Representative representative) {
this.representative = representative;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Customer customer = (Customer) o;
return id == customer.id
&& activity == customer.activity
&& Objects.equals(name, customer.name)
&& Objects.equals(company, customer.company)
&& Objects.equals(country, customer.country)
&& Objects.equals(date, customer.date)
&& status == customer.status
&& Objects.equals(representative, customer.representative);
}
@Override
public int hashCode() {
return Objects.hash(id, name, company, country, date, status, activity, representative);
}
}
public class Country implements Serializable, Comparable<Country> {
private int id;
private String name;
private String code;
private Locale locale;
private boolean rtl;
public Country() {
}
public Country(int id, Locale locale) {
this(id, locale.getDisplayCountry(), locale.getCountry().toLowerCase(), locale);
}
public Country(int id, Locale locale, boolean rtl) {
this(id, locale.getDisplayCountry(), locale.getCountry().toLowerCase(), locale);
this.rtl = rtl;
}
public Country(int id, String name, String code) {
this(id, name, code, null);
}
public Country(int id, String name, String code, Locale locale) {
this.id = id;
this.name = name;
this.code = code;
this.locale = locale;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public String getLanguage() {
return locale == null ? "en" : locale.getLanguage();
}
public String getDisplayLanguage() {
return locale == null ? "English" : locale.getDisplayLanguage();
}
public boolean isRtl() {
return rtl;
}
public void setRtl(boolean rtl) {
this.rtl = rtl;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Country country = (Country) o;
return id == country.id
&& Objects.equals(name, country.name)
&& Objects.equals(code, country.code);
}
@Override
public int hashCode() {
return Objects.hash(id, name, code);
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Country o) {
return name.compareTo(o.name);
}
}
public enum CustomerStatus {
QUALIFIED,
UNQUALIFIED,
NEGOTIATION,
NEW,
RENEWAL,
PROPOSAL;
public static CustomerStatus random() {
Random random = new Random();
return values()[random.nextInt(values().length)];
}
}
public class Representative implements Serializable, Comparable<Representative> {
private static final long serialVersionUID = 1L;
private String name;
private String image;
public Representative() {
}
public Representative(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Representative that = (Representative) o;
return Objects.equals(name, that.name)
&& Objects.equals(image, that.image);
}
@Override
public int hashCode() {
return Objects.hash(name, image);
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Representative o) {
return name.compareTo(o.name);
}
}
@Named
@ApplicationScoped
public class CustomerService {
private Random random = new SecureRandom();
private Country[] countries;
private Representative[] representatives;
private String[] firstNames;
private String[] lastNames;
private String[] companies;
@PostConstruct
public void init() {
countries = new Country[]{
new Country(0, "Argentina", "ar"),
new Country(1, "Australia", "au"),
new Country(2, "Brazil", "br"),
new Country(3, "Canada", "ca"),
new Country(4, "Germany", "de"),
new Country(5, "France", "fr"),
new Country(6, "India", "in"),
new Country(7, "Italy", "it"),
new Country(8, "Japan", "jp"),
new Country(9, "Russia", "ru"),
new Country(10, "Spain", "es"),
new Country(11, "United Kingdom", "gb")};
companies = new String[]{"Benton, John B Jr", "Chanay, Jeffrey A Esq", "Chemel, James L Cpa", "Feltz Printing Service",
"Printing Dimensions", "Chapman, Ross E Esq", "Morlong Associates", "Commercial Press", "Truhlar And Truhlar Attys",
"King, Christopher A Esq", "Dorl, James J Esq", "Rangoni Of Florence", "Feiner Bros", "Buckley Miller Wright",
"Rousseaux, Michael Esq"};
representatives = new Representative[]{
new Representative("Amy Elsner", "amyelsner.png"),
new Representative("Anna Fali", "annafali.png"),
new Representative("Asiya Javayant", "asiyajavayant.png"),
new Representative("Bernardo Dominic", "bernardodominic.png"),
new Representative("Elwin Sharvill", "elwinsharvill.png"),
new Representative("Ioni Bowcher", "ionibowcher.png"),
new Representative("Ivan Magalhaes", "ivanmagalhaes.png"),
new Representative("Onyama Limba", "onyamalimba.png"),
new Representative("Stephen Shaw", "stephenshaw.png"),
new Representative("Xuxue Feng", "xuxuefeng.png")};
firstNames = new String[]{"James", "David", "Jeanfrancois", "Ivar", "Tony",
"Adams", "Claire", "Costa", "Juan", "Maria", "Jennifer",
"Stacey", "Leja", "Morrow", "Arvin", "Darci", "Izzy",
"Ricardo", "Clifford", "Emily", "Kadeem", "Mujtaba", "Aika",
"Mayumi", "Misaki", "Silvio", "Nicolas", "Antonio",
"Deepesh", "Aditya", "Aruna", "Jones", "Julie", "Smith",
"Johnson", "Francesco", "Salvatore", "Kaitlin", "Faith",
"Maisha", "Jefferson", "Leon", "Rodrigues", "Alejandro",
"Munro", "Cody", "Chavez", "Sinclair", "Isabel", "Octavia",
"Murillo", "Greenwood", "Wickens", "Ashley"};
lastNames = new String[]{"Butt", "Darakjy", "Venere", "Paprocki", "Foller",
"Morasca", "Tollner", "Dilliard", "Wieser", "Marrier", "Amigon",
"Maclead", "Caldarera", "Ruta", "Albares", "Poquette", "Garufi",
"Gaucho", "Rim", "Whobrey", "Flosi", "Nicka", "Inouye",
"Kolmetz", "Royster", "Slusarski", "Iturbide", "Caudy",
"Chui", "Kusko", "Figeroa", "Vocelka", "Stenseth", "Glick",
"Sergi", "Shinko", "Stockham", "Ostrosky", "Gillian",
"Rulapaugh", "Schemmer", "Oldroyd", "Campain", "Perin",
"Ferencz", "Saylors", "Briddick", "Waycott", "Bowley", "Malet",
"Malet", "Bolognia", "Nestle", "Doe"};
}
public List<Customer> getCustomers(int number) {
List<Customer> customers = new ArrayList<>();
for (int i = 0; i < number; i++) {
customers.add(
new Customer(i + 1000, getName(), getCompany(), getCountry(), getDate(),
CustomerStatus.random(), getActivity(), getRepresentative()));
}
return customers;
}
public List<Country> getCountries() {
return Arrays.asList(countries);
}
public CustomerStatus[] getCustomerStatus() {
return CustomerStatus.values();
}
public List<Representative> getRepresentatives() {
return Arrays.asList(representatives);
}
private String getName() {
return firstNames[random.nextInt(firstNames.length)] + Constants.SPACE
+ (char) (random.nextInt(26) + 'A') + Constants.SPACE
+ lastNames[random.nextInt(lastNames.length)];
}
private Country getCountry() {
return countries[random.nextInt(countries.length)];
}
private String getCompany() {
return companies[random.nextInt(companies.length)];
}
private LocalDate getDate() {
LocalDate now = LocalDate.now();
long randomDay = ThreadLocalRandom.current().nextLong(now.minusDays(30).toEpochDay(), now.toEpochDay());
return LocalDate.ofEpochDay(randomDay);
}
private int getActivity() {
return random.nextInt(100);
}
private Representative getRepresentative() {
return representatives[random.nextInt(representatives.length)];
}
}
@Named("dtLazyView")
@ViewScoped
public class LazyView implements Serializable {
private LazyDataModel<Customer> lazyModel;
private Customer selectedCustomer;
@Inject
private CustomerService service;
@PostConstruct
public void init() {
lazyModel = new LazyCustomerDataModel(service.getCustomers(200));
}
public LazyDataModel<Customer> getLazyModel() {
return lazyModel;
}
public Customer getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(Customer selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public void setService(CustomerService service) {
this.service = service;
}
public void onRowSelect(SelectEvent<Customer> event) {
FacesMessage msg = new FacesMessage("Customer Selected", String.valueOf(event.getObject().getId()));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}