Coloring Table Cells Conditionally in SAP UI5
Introduction
This document helps how to color table cell/row conditionally in SAP UI5.
Step by Step Process
To create a Table refer this example in the Demo Kit: SAPUI5 SDK – Demo Kit – Table
We can color individual table cell or entire row based on condition by setting the css style class.
Here we will see a simple example to color the table cell based on the amount value.
Here is the code for the UI5 application.
<!DOCTYPE HTML>
<html>
<head>
<title>Table Cell Color Demo </title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons, sap.ui.table"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<style type="text/css">
.green {
background-color: #66FF33;
}
.red {
background-color: #FF3300;
}
.yellow {
background-color: #FFFF66;
}
</style>
<script>
// Model Data (local)
var aData = [{
order: "456",
customer: "SAP",
curr: "EUR",
amount: 30000
}, {
order: "457",
customer: "Jateco",
curr: "EUR",
amount: 1300
}, {
order: "458",
customer: "SAP",
curr: "EUR",
amount: 1200
}, {
order: "459",
customer: "Sorali",
curr: "EUR",
amount: 750
}, {
order: "460",
customer: "Ariba",
curr: "EUR",
amount: 1500
}, ];
// Define a table
var oTable = new sap.ui.table.Table({
title: "Order Details", // heading of the table
visibleRowCount: 5, // Visible no of Rows of table
selectionMode: sap.ui.table.SelectionMode.Single, // Singe or Multi
navigationMode: sap.ui.table.NavigationMode.Paginator, //Paginator or Scrollbar
enableColumnReordering: true, // Allows you to drag and drop the column and reorder the position of the column
width: "800px"
});
// Add table Columns
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Order" // Creates an Header with value defined for the text attribute
}),
template: new sap.ui.commons.TextView({
text: '{order}', // binds the value into the text field defined using JSON
}),
width: "150px" // width of the column
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Customer"
}),
template: new sap.ui.commons.TextView({
text: '{customer}'
}),
width: "150px"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Currency"
}),
template: new sap.ui.commons.TextView({
text: '{curr}'
}),
width: "100px"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Amount"
}),
template: new sap.ui.commons.TextView().bindProperty("text", "amount", function(cellValue) {
// remove styles else it will overwrite
this.removeStyleClass('green');
this.removeStyleClass('yellow');
this.removeStyleClass('red');
// Set style Conditionally
if (cellValue >= 1500) {
this.addStyleClass('green');
} else if(cellValue < 1500 && cellValue > 1000) {
this.addStyleClass('yellow');
} else{
this.addStyleClass('red');
}
return cellValue;
}),
width: "100px"
}));
//Create a model and bind the table rows to this model
var oModel = new sap.ui.model.json.JSONModel(); // created a JSON model
oModel.setData({ // Set the data to the model using the JSON object defined already
modelData: aData
});
oTable.setModel(oModel);
oTable.bindRows("/modelData"); // binding table rows
//Place the Table on the UI
oTable.placeAt("orders");
</script>
</head>
<body class="sapUiBody">
<div id="orders"></div>
</body>
</html>
Result:
Now we can see, the table cells are colored accordingly to the condition
We will now see how to color the entire row conditionally based on the amount value.
Here is the Code:
<!DOCTYPE HTML>
<html>
<head>
<title>Table Row Color Demo </title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons, sap.ui.table"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<style type="text/css">
.green {
background-color: #66FF33;
}
.red {
background-color: #FF3300;
}
.yellow {
background-color: #FFFF66;
}
</style>
<script>
// Model Data (local)
var aData = [{
order: "456",
customer: "SAP",
curr: "EUR",
amount: 30000
}, {
order: "457",
customer: "Jateco",
curr: "EUR",
amount: 1300
}, {
order: "458",
customer: "SAP",
curr: "EUR",
amount: 1200
}, {
order: "459",
customer: "Sorali",
curr: "EUR",
amount: 750
}, {
order: "460",
customer: "Ariba",
curr: "EUR",
amount: 1500
}, ];
// Define a table
var oTable = new sap.ui.table.Table({
title: "Order Details",
visibleRowCount: 5,
selectionMode: sap.ui.table.SelectionMode.Single,
navigationMode: sap.ui.table.NavigationMode.Scrollbar,
width: "800px"
});
// Add table Columns
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Order"
}),
template: new sap.ui.commons.TextView({
text: '{order}',
}),
width: "150px"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Customer"
}),
template: new sap.ui.commons.TextView({
text: '{customer}'
}),
width: "150px"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Currency"
}),
template: new sap.ui.commons.TextView({
text: '{curr}'
}),
width: "100px"
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Amount"
}),
template: new sap.ui.commons.TextView({
text: '{amount}'
}),
width: "100px"
}));
//Create a model and bind the table rows to this model
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
modelData: aData
});
oTable.setModel(oModel);
oTable.bindRows("/modelData");
//Place the Table on the UI
oTable.placeAt("orders");
// Set Row Color Conditionally
var colorRows = function() {
var rowCount = oTable.getVisibleRowCount(); //number of visible rows
var rowStart = oTable.getFirstVisibleRow(); //starting Row index
var currentRowContext;
for (var i = 0; i < rowCount; i++) {
currentRowContext = oTable.getContextByIndex(rowStart + i); //content
// Remove Style class else it will overwrite
oTable.getRows()[i].$().removeClass("yellow");
oTable.getRows()[i].$().removeClass("green");
oTable.getRows()[i].$().removeClass("red");
var cellValue = oModel.getProperty("amount", currentRowContext); // Get Amount
// Set Row color conditionally
if (cellValue >= 1500) {
oTable.getRows()[i].$().addClass("green");
} else if (cellValue < 1500 && cellValue > 1000) {
oTable.getRows()[i].$().addClass("yellow");
} else {
oTable.getRows()[i].$().addClass("red");
}
}
}
$(document).ready(function() {
// Attach Scroll Handler
oTable._oVSb.attachScroll(function() {
colorRows()
});
colorRows(); // Color Rows initially
});
</script>
</head>
<body class="sapUiBody">
<div id="orders"></div>
</body>
</html>
Result:
Now we can see, the whole table rows are colored based on the amount value
This should also work even if we change the Visible Row count of table.
Result after changing the Visible row count to 3:
After Scroll:
You need to modify the code if you use the Navigation mode as Paginator instead of Scrollbar.
Here is the code snippet for Navigation Mode – Paginator:
// Set Row Color Conditionally
var colorRows = function() {
var rowCount = oTable.getVisibleRowCount(); //number of visible rows
var rowStart = rowCount * ( oTable._oPaginator.getCurrentPage() - 1); //starting Row index
var currentRowContext;
for (var i = 0; i < rowCount; i++) {
currentRowContext = oTable.getContextByIndex(rowStart + i); //content
// Remove Style class else it will overwrite
oTable.getRows()[i].$().removeClass("yellow");
oTable.getRows()[i].$().removeClass("green");
oTable.getRows()[i].$().removeClass("red");
var cellValue = oModel.getProperty("amount", currentRowContext); // Get Amount
// Set Row color conditionally
if (cellValue >= 1500) {
oTable.getRows()[i].$().addClass("green");
} else if (cellValue < 1500 && cellValue > 1000) {
oTable.getRows()[i].$().addClass("yellow");
} else if (cellValue < 1000 && cellValue > 0) {
oTable.getRows()[i].$().addClass("red");
}
}
}
$(document).ready(function() {
//Attach Page handler
oTable._oPaginator.attachPage(function(){
colorRows()
});
colorRows(); // Color Rows initially
});
Result:
Here, I just demonstrated a simple example to color table cells/rows conditionally based on cell value. You can use according to your requirements( with nice color codes, not the ugly colors as demonstrated 😛 ).
good blog..have you tried re-sizing the columns after the coloring is done?? Do you see any side effects??
Hi,
Thank you for your feedback. Yes.,The colors remain same ever if you resize the columns in the first way( for single cell coloring) as we are coloring the template but not the column.
Before:
After:
Where as in the second case( coloring the whole table row), the colors won't remain when you resize the columns. You need to color the rows back in the handler event of resize columns, just as I handled here for scrolling and pagination in the demo.
Regards,
Kiran
Hi Kiran,
i have above situation where colors are not coming when column size changed i tried following code with both _onColumnResize and _onColumnResized both not working.
columnResize : function(oEvent){
$(document).ready(function(){
oTable._onColumnResize(function(){that.colorRows();});
}
}
Can you add your code to onAfterRendering method of the corresponding controller, if you have not done.
Regards,
Seyed Ismail
Hi Seyed,
Thanks for your response,
i wrote below logic in onAfterRendering this case colors are not coming at all
$(document).ready(function() {
oTable._onColumnResize(function(){
sap.ui.getCore().byId("mainid1").getController().colorRows();
});
});
Can you remove $(document).ready(function() and try?
Tried below,
onAfterRendering: function() {
oTable._onColumnResize(function(){
sap.ui.getCore().byId("mainid1").getController().colorRows();
});
Saying oTable is not defined.
You should read the table into oTable first.
onAfterRendering: function() {
var oTable = sap.ui.getCore().byId("id of your table");
oTable._onColumnResize(function(){
sap.ui.getCore().byId("mainid1").getController().colorRows();
});
Your way of coloring rows definitely does no good to the table performance... It's a shame that UI5 itself does not provide a way to do this btw.
Hi. I followed the blog but I have a table with: fixedColumnCount: 2. In my program with this value change the color of cells but only the columns that are not fixed.
Thank you for this post!
You saved my life!
Only question:
how did you understand that the cell value is stored in the "cellvalue"?
thank you in advance.
I hope it is the syntax of sap.ui.commons.TextView().bindProperty.
That is how this has been built.
Awesome presentation. Thanks a lot.
But I have a small difficulty. My data is coming from Gateway and it is a bit larger data, hence it is taking some time to load.
My logic to change the color is : The first line, I am displaying as TOTAL, should be changed.
When my table is loaded with data, it doesn't change color. But, when I scroll it is changing. I don't know where am I going wrong.
see my code:
Thanks a lot!
Seyed Ismail.
Hello,
Did you tried to also call the colorRows() function as soon as the table has finished rendering?
You can attach a function call for table "onAfterRendering" like this:
var oTableNASummary = sap.ui.getCore().byId("idTableNASummary");
oTableNASummary .addEventDelegate({
onAfterRendering: function(){colorRows();}
}, this);
On another note, nice example Kiram !
Hi Alex,
It didn't work. Nevertheless, I fixed the issue by adding colorRows to onAfterRendering method of the corresponding controller.
Thanks.
Seyed Ismail.
Hi Kiran,
Thank you so much for sharing your knowledge.
i am tring this i have problem in which i displaying table in shell on first menu option.
So when ever page loads colors should come but for initial page colors are not coming i had written in onAfterRendering as below
});
}
in this case mainid1 is the view id and shell1 is the shell id, oTable.getContectByIndex(1)
is not selecting any value.
My question is placing this code in onAfterRendering is not correct if yes where can i try for initial display of colors.
Have you tried removing/adding table rows dynamically with this approach? When I set valuestate-s or add style classes and afterwards change table (like add or remove table row) then the coloring is removed....
Hi,
Nice blog!!
Actually, I am trying to do the same with sap.m.table. But looks like I do not find the getRows() method for the sap.m.table.
Does it mean we can't do this with sap.m.table?
Or is there an alternate way of doing it through sap.m.table?
I would really appreciate your response.
Thanks,
Bhavik
Please refer my blog : sap.m.Table - Conditional Cell Coloring based on value
Thanks,
Seyed Ismail.
Hello Kiran,
In my Sap UI Table am using drop downs.Coloring for cells is not applying for drop downs.Could you please let me know the ccs for coloring Dropdowns in aTable
In the new version of UI5 libraries ver 1.38.7 the attribute oTable._oVSb is no longer available. Any knows the alternative?
in index.html modify resource like below
"https://sapui5.hana.ondemand.com/1.36.11/resources/sap-ui-core.js"
instead of
"https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
Hi Mantri,
I am asking about the alternative of oTable._OVSb in version 1.38.7 of UI5 libraries. Not about how to use the new libraries.
Hi Kiran Kumar Valluru.
Thanks for yuor contribute.
I have a problem with your solution realtive to single cell colored.
If the cell is empty, the style is no apply!
Furthermore, how i can apply background color to single header column cell?
Thanks.
Hello Kiran,
very nice blog, thanks for your contribution and very helpful blog, i have a same scenario where i have a field coming from the backend and based on the field data i need to style the entire row color after rendering.
I have no action to do like scrolling or pagenator so on.. i am using sap.ui.table.
Could you please help me on this. how to color the entire row on a condition based without any event or performing action.
Furthermore if you need any information i am ready to give you.
Thanks in advance.
That solution didn't work for me 🙁
Since oTable.getRows() only gets the visible rows on the screen, I can't reach and change the color of the coming rows in the table. In my table I have 20 rows but in the first place 9 of them are visible on the screen. I have to color lets say 7th and 12th ones. I am able to color the 7th one but when the loop turns for 12th one, I get dump of undefined because oTable.getRows() couldnt find the 12th row. And because of that 7th one stays colorful and when I scroll down the 7th row of the table is colorful to the end of the table.
Any help would be appreciated.
Best,
Merve
Hi Merve, do you find solution for getRows(), i need all the rows not only visible rows. I have 15 rows but only 8 are visible, i need the 9, 10 ... for asign a color.
Regards 🙂
Hi All!
have somebody tried to implement the same logic for ui.table but without creating table's structure from the controller? I'm following the mvc principle and my table is declared solely in my view.
Ideally, I'm looking for the solution to paint my table conditionally for each row/col.
however informative, but I think you are changing the Text Background color and not cell background. This sort of leads to rest of the issue. to Ensure this works, I have to set the width of text as 100% always, we need to figure out a way to change the <td> color on conditions.
The main problem for me is getRows() method. It returns only visible rows, not all the records in the table. Therefore, impossible color remaining rows properly. Is there any alternative to getRows()? BTW, getContextByIndex does not work. Thanks!
Actually the property table._oVSb. is undefined, not exists. Any suggestion or alternative?
Regards