In a recent post, Kathy Brown showed how to alternate row colors, in XPages. In this post, I’ll show how to take that a step further and dynamically set the row color based on data in the row.
You can compute the style class of each row in a view panel or repeat control (or data table or data view, etc), so you have the ability to check the data in each view entry and set a style class accordingly. Let’s start with the view panel.
In my example, I have a list of tasks. When a task is about to expire, I want the row to appear with a yellow background. When the task has expired, I want the row to appear with a red background.
Here’s a View Panel using this technique:
This requires 3 steps:
- Create CSS style classes for the row colors (and include the style sheet on the page)
- Set the var property of the view panel
- Compute the style class to use for the row, based on the data
1. Create CSS Style Classes for the Row Colors
I have defined these styles in a style sheet that is included on my page:
.yellowRow { background-color: #FFFF00; } .redRow { background-color: #FF0000; }
2. Set the var property of the view panel
In order to compute the class based on data in each view entry, we need to have the ability to read data from the view entry. The var property of the view panel gives us that handle.
3. Compute the style class to use for the row, based on the data
Now that I have styles defined and a handle to the view entry, I can compute the style class for each row. To do so, select the view panel properties, select the Style subtab, and select the rowClasses property. Next to the Class property, click on the diamond to open up an SSJS window and add the code to compute the style class.
This code will read the value of the ‘status’ column and return a class name to use for the row accordingly.
var status = varTask.getColumnValue('Status'); var cssClass = ''; if (status == 'Expiring') { cssClass = 'yellowRow'; } else if (status == 'Late') { cssClass = 'redRow'; } return cssClass;
Working with a Repeat Control
All of the same concepts apply. The difference is that you don’t have a built-in styleClass property to use. Assuming your repeat control contains a table, you can compute the style class on the xp:tr tag within the xp:repeat tag.
It can be difficult to try to select the xp:tr tag directly, but you can click on the first cell in the row and then locate the xp:tr tag either via the Outline view or in the page source. Once you have the xp:tr tag selected, you can compute its styleClass property and use the same code as shown above, provided you have defined the same var name for the repeat control.
