DEV Community

KIranuknow
KIranuknow

Posted on • Updated on

SAPUI5 - Table Cell Coloring

We can color the table cells in SAPUI5's sap.ui.table using css.
There are two ways, one is to use customData in the template and formatter.

//using Javascript code for dynamically adding columns with css coloring.


 var oTable = new Table("idMyTable", {
                columns: [
                    new Column({
                        label: new Label({ text: "City" }),
                        template: new Text({
                            text: "{model>city}",
                            customData: [
                                new sap.ui.core.CustomData({
                                    key: "color",
                                    value: "{model>color}"
                                })
                            ]
                        }).addStyleClass("customText")
                    })
                ]
            });

//call the below function from the above column addition
 oTable.getRows().forEach(function(oRow) {
                        oRow.getCells().forEach(function(oCell) {
                            var sColor = oCell.data("color");
                            if (sColor) {
                                oCell.addStyleClass("customTextColor-" + sColor.toLowerCase());
                            }
                        });
                    });
Enter fullscreen mode Exit fullscreen mode

Formatter:

var oNewColumn = new Column({
                label: new Label({ text: "Weight" }),
                template: new Text({
                    text: {
                        path: "Weight",
                        formatter: this.formatColor
                    }
                })
            });

            oTable.addColumn(oNewColumn);
Enter fullscreen mode Exit fullscreen mode
//Formatter function
formatColor: function(sWeight) {
if (sWeight > 100) {
    this.addStyleClass("red");
} else {
    this.addStyleClass("green");
}

});
Enter fullscreen mode Exit fullscreen mode

3rd Method

Top comments (0)