Skip to Content

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

table_cell_color.JPG

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

table_row_color.JPG

This should also work even if we change the Visible Row count of table.

Result after changing the Visible row count to 3:

table_row_color1.JPG

After Scroll:

table_row_color2.JPG

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:

table_row_color3.JPG

table_row_color4.JPG

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 😛 ).



To report this post you need to login first.

26 Comments

You must be Logged on to comment or reply to a post.

    1. Kiran Kumar Valluru Post author

      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:

      before.JPG

      After:

      after.JPG

      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

      (0) 
      1. SRIHARSHA kasukurthi

        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();});

        }

        }

        (0) 
          1. SRIHARSHA kasukurthi

            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();

            });

            });

            (0) 
              1. SRIHARSHA kasukurthi

                Tried below,

                onAfterRendering: function() {

                oTable._onColumnResize(function(){

                     sap.ui.getCore().byId(“mainid1”).getController().colorRows();

                });

                Saying oTable is not defined.

                (1) 
                1. Seyed Ismail

                  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();

                  });

                  (0) 
  1. Alexander Ryabov

    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.

    (0) 
  2. Seyed Ismail

    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:

    var oTableNASummary = sap.ui.getCore().byId(“idTableNASummary”);
    oTableNASummary._oVSb.attachScroll(function() {
    oCurrent.colorRows();  // working fine
    });

    $(document).ready(function() { // optional
    oCurrent.colorRows();// not working at all
    });//optional     

    Thanks a lot!

    Seyed Ismail.

    (0) 
    1. Alex -

      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 !

      (0) 
      1. Seyed Ismail

        Hi Alex,

        It didn’t work. Nevertheless, I fixed the issue by adding colorRows to onAfterRendering method of the corresponding controller.

        Thanks.

        Seyed Ismail.

        (0) 
  3. SRIHARSHA kasukurthi

    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

    onAfterRendering: function() {
    oTable = sap.ui.getCore().byId(“mainid1”).getController().loadRecentActivities();

    oTable._oVSb.attachScroll(function() { sap.ui.getCore().byId(“mainid1”).getController().colorRowsrecent();

             });

    sap.ui.getCore().byId(“Shell1”).addContent(oTable);
    sap.ui.getCore().byId(“mainid1”).getController().colorRowsrecent();

    }

    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.

    (0) 
  4. guest 201232

    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….

    (0) 
  5. Devisha Bhavik

    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

    (0) 
  6. Mantri Shekar

    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

    (0) 
  7. Massimiliano Sacilotto

    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.

    (0) 
  8. Vikas B

    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.

    (0) 
  9. Merve Gul

    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

    (0) 

Leave a Reply