Quantcast
Channel: SAPUI5 Developer Center
Viewing all articles
Browse latest Browse all 789

Coloring Table Cells Conditionally in SAP UI5

$
0
0

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




Viewing all articles
Browse latest Browse all 789

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>