The dataTable
component provides conditional coloring on rows, which can be styled based on conditions. The row styling utilizes the rowStyleClass
attribute that has a condition as the EL expression.
In this recipe, we will demonstrate the conditional coloring on rows for countries with GDP (gross domestic product) less than $3,500,000.
A basic definition of a color-coded table that displays a list of countries with their GDPs is given here:
<p:dataTable value="#{dataTableColoringBean.countryGdpList}" var="countryGdp" rowStyleClass="#{countryGdp.gdp le 3500000 ? 'colored' : ''}"> <p:column headerText="Name" sortBy="#{countryGdp.name}"> #{countryGdp.name} </p:column> <p:column headerText="GDP (Millions of US $)"> #{countryGdp.gdp} </p:column> </p:dataTable>
The colored style definition used in rowStyleClass
could be as simple as the following:
<style type="text/css"> .colored { background-color: #FF0000; color: #FFFFFF; } </style>
After sorting by name, the end result shows four colored rows here:
With the rowStyleClass
attribute, a style class can be defined for each row according to the country's GDP as rowStyleClass="#{countryGdp.gdp le 3500000 ? 'colored' : ''}"
. Arithmetic, logical, or relational operators of JSF Expression Language can be used to define the condition.
This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on application servers compatible with Servlet 3.x, such as JBoss WildFly and Apache TomEE.
The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter11/dataTableColoring.jsf
.