SAP UI5 – Data binding without XML view for the sap.m.Table component

Here I’ll describe the best method I’ve found to bind data to the sap.m.Table component without using XML view, so only with JavaScript, programmatically.

Link to the sap.m.Table component in the SAP UI5 documentation.

First, you need to declare your dataset:

var oData = {
    'History': {
        'Entries': [
            {
                'Type': 'nonFolder',
                'Name': 'LCMCompare',
                'Time': 'Jan 9, 2017 2:01 PM',
                'modifiedCount': '1'
            },
            {
                'Type': 'nonFolder',
                'Name': 'Another one',
                'Time': 'Jan 2, 2017 5:55 PM',
                'modifiedCount': '9'
            },
            {
                'Type': 'nonFolder',
                'Name': 'First comparison',
                'Time': 'Jan 9, 2017 4:41 PM',
                'modifiedCount': '4'
            }
        ]
    }
};

After that, you need to declare your columns definitions:

var oTable = new UI5Table({
    headerText: 'Compared:',
    columns: [
        new UI5Column({
            header: new UI5Label({
                text: 'Type'
            })
        }),
        new UI5Column({
            header: new UI5Label({
                text: 'Comparison Name'
            })
        }),
        new UI5Column({
            header: new UI5Label({
                text: 'Date/Time'
            })
        }),
        new UI5Column({
            header: new UI5Label({
                text: 'Difference'
            })
        })
    ]
});

Now, it’s time to declare the table and to define the binding between the data and the columns: (in my case, I’m naming history as the root as my datasource)

var oModelTable = new sap.m.JSONModel(oData);
oTable.setModel(oModelTable, 'history');
var oTemplate = new UI5ColumnListItem({
    cells : [
        new UI5Text({
            text : '{history>Type}'
        }),
        new UI5Text({
            text : '{history>Name}'
        }),
        new UI5Text({
            text : '{history>Time}'
        }),
        new UI5Text({
            text : '{history>modifiedCount}'
        })
    ]
});
oTable.bindItems('history>/History/Entries', oTemplate);

The last line in this example will bind your data following the root > and the path to the array to iterate through. Your table will be rendered with the data in your oData object. I would suggest to attach this binding with an object in your store, so changes will appear automatically.

Preview of the result: sap-m-table_ui5_result

Leave a Reply

Your email address will not be published.