Search code examples
odatasapui5

creating dynamic table with data from odata service in ui5


I'm a complete newb on sap ui5.

I'm trying to generating a table on my webpage generated in sap web ide. The data for this table is a .json file accessed via odata service.

I've come this far:

oModel is generated:

function initModel() {
    var sUrl = "/sap/opu/odata/sap/ZGWS_someService/CollectionSet?$format=json";
    var oModel = new sap.ui.model.odata.ODataModel(sUrl, true);
    sap.ui.getCore().setModel(oModel);
}

now I want to generate a table on my html site with the data in the .json file. So I have to create columns based on the properties of the items and then filling the rows with the current data.

.json looks like this:

{
"d": {
"results": [
{
"property1": "123",
"property2": "346"
},
{
"property1": "123",
"property2": "555"
}

I have no solution for this yet - can you help me out?

greetz, simon


Solution

  • I created the table in the controller and sorted the data via lodash.

    Is that good practice?

    var oTable = this.byId("table");
            oTable.addColumn(new sap.ui.table.Column({
                label: new sap.ui.commons.Label({
                    text: "Info1"
                }),
                sortProperty: "INTST",
                template: new sap.ui.commons.TextView().bindProperty("text", "key")
            }));
            oTable.addColumn(new sap.ui.table.Column({
                label: new sap.ui.commons.Label({
                    text: "Count"
                }),
                template: new sap.ui.commons.TextView().bindProperty("text", "value")
            }));
            $
                .ajax({
                    url: '/.../ServiceSet',
                    jsonpCallback: 'getJSON',
                    contentType: "application/json",
                    dataType: 'json',
                    success: function(data, textStatus, jqXHR) {
                        var oModel = new sap.ui.model.json.JSONModel();
                        oModel.setData(data);
                        sap.ui.getCore().setModel(oModel);
                        //Create a model and bind the table rows to this model
                        //Get the forecastday array table from txt_forecast object
                        var aData = oModel.getProperty("/d/results");
                        var aData2 = _.countBy(_.map(aData, function(d) {
                            return d.VALUE;
                        }));
                        var aData3 = Object.keys(aData2).sort().map(key => ({
                            key,
                            value: aData2[key]
                        }));
                        oModel.setData({
                            modelData: aData3
                        });
                        oTable.setModel(oModel);
                    }
                });
            oTable.bindAggregation("rows", {
                path: "/modelData"
            });