Skip to Content
Technical Articles
Author's profile photo mundru venkatesh

SAPUI5 – Pagination in sap.m Table on button click using JSON Data

Hi, in this blog I’m going to explain the pagination in sap.m Table with json data.

In this example, I am using Northwind model Products entity set data that stored in json model that contains 20 records and I have to display 5 records per click.

So, I have placed four nav buttons for First page (<<), Previous page (<), Next page (>), Last page (>>) with page count information and then some magical code.

Firstly, in Products View use the following code to display table data and buttons.

<mvc:View controllerName="com.zproducts.controller.Products"
    xmlns:mvc="sap.ui.core.mvc" displayBlock="true"
    xmlns="sap.m">
    <Page id="page" title="{i18n>title}">
        <content>
            <Table id="idProductsTable" busy="{ProductsModel>/isProductsDataLoading}" items="{ path: 'ProductsModel>/tableData'}">
                <columns>
                    <Column >
                        <Text text="Product Id" />
                    </Column>
                    <Column >
                        <Text text="Product Name" />
                    </Column>
                </columns>
                <items>
                    <ColumnListItem>
                        <cells>
                            <ObjectIdentifier title="{ProductsModel>ProductID}" />
                            <Text text="{ProductsModel>ProductName}" />
                        </cells>
                    </ColumnListItem>
                </items>
            </Table>
            <OverflowToolbar >
                <ToolbarSpacer />
                <Button id="BtnFirstPressId" icon="sap-icon://close-command-field" press="onFirstPress" tooltip="First" enabled="{NavModel>/firstPageBtnEnable}" />
                <Button id="BtnPreviousPressId" icon="sap-icon://navigation-left-arrow" press="onPreviousPress" tooltip="Previous" enabled="{NavModel>/firstPageBtnEnable}" />
                <Text id="PageTextId" text="{i18n>page} {ProductsModel>/page} {i18n>of} {ProductsModel>/totalPages}" />
                <Button id="BtnNextPressId" icon="sap-icon://navigation-right-arrow" press="onNextPress" tooltip="Next" enabled="{NavModel>/nextPageBtnEnable}" />
                <Button id="BtnLastPressId" icon="sap-icon://open-command-field" press="onLastPress" tooltip="Last" enabled="{NavModel>/nextPageBtnEnable}" />
            </OverflowToolbar>
        </content>
    </Page>
</mvc:View>

 

Secondly in controller in onInit function paste the following code to define json models and read products data using Northwind oData model.

onInit: function () {
                var that = this;

                //Stores products data and indexes data
                var oProductsModel = new JSONModel ({
                    productsData: [],
                    isProductsDataLoading: true,
                    tableData: [],
                    startIndex: 0,
                    endIndex: 0,
                    noOfTableRows: 5,
                    page: 0,
                    totalPages: 0
                });
                that.getView().setModel(oProductsModel, "ProductsModel");

                //Stores Nav buttons enable properties
                var oNavModel = new JSONModel({
                    firstPageBtnEnable: false,
                    nextPageBtnEnable: false
                });
                that.getView().setModel(oNavModel, "NavModel");

                var oModel = that.getOwnerComponent().getModel("NorthwindModel");
                oModel.read("/Products", {
                    success: function (oData) {
                        //Stores the Produsts data
                        that.getView().getModel("ProductsModel").setProperty("/productsData", oData.results);
                        that.getView().getModel("ProductsModel").setProperty("/isProductsDataLoading", false);
                        //Sets total page count
                        var noOfTableRows = parseInt(that.getView().getModel("ProductsModel").getProperty("/noOfTableRows"));
                        that.getView().getModel("ProductsModel").setProperty("/totalPages", Math.ceil(oData.results.length / noOfTableRows));
                        //To get data for first view
                        that.onFirstPress();
                    },
                    error: function (oError) {
                        that.getView().getModel("ProductsModel").setProperty("/isProductsDataLoading", false);
                    }
                });
            }

 

Now Paste the following code in the controller to handle nav buttons functionality and current page value.

            //set first selected number of visible rows to table
            onFirstPress: function () {
                var that = this;
                var data = that.getView().getModel("ProductsModel").getProperty("/productsData");
                var noOfTableRows = parseInt(that.getView().getModel("ProductsModel").getProperty("/noOfTableRows"));
                var newData = data.slice(0, noOfTableRows);

                //To set Table Data
                that.fnSetTableData(newData, 0, noOfTableRows - 1, 1);
            },

            //set previous selected number of visible rows to table
            onPreviousPress: function () {
                var that = this;
                var data = that.getView().getModel("ProductsModel").getProperty("/productsData");
                var noOfTableRows = parseInt(that.getView().getModel("ProductsModel").getProperty("/noOfTableRows"));
                var startIndex = that.getView().getModel("ProductsModel").getProperty("/startIndex");
                var newData = data.slice(startIndex - noOfTableRows, startIndex);

                //To set Table Data
                that.fnSetTableData(newData, startIndex - noOfTableRows, startIndex - 1, that.getView().getModel("ProductsModel").getProperty("/page") - 1);

            },

            //set next selected number of visible rows to table
            onNextPress: function () {
                var that = this;
                var data = that.getView().getModel("ProductsModel").getProperty("/productsData");
                var noOfTableRows = parseInt(that.getView().getModel("ProductsModel").getProperty("/noOfTableRows"));
                var endIndex = that.getView().getModel("ProductsModel").getProperty("/endIndex");
                var newData = data.slice(endIndex + 1, endIndex + 1 + noOfTableRows);

                //To set Table Data
                that.fnSetTableData(newData, endIndex + 1, endIndex + noOfTableRows, that.getView().getModel("ProductsModel").getProperty("/page") + 1);
            },

            //set last selected number of visible rows to table
            onLastPress: function () {
                var that = this;
                var data = that.getView().getModel("ProductsModel").getProperty("/productsData");
                var noOfTableRows = parseInt(that.getView().getModel("ProductsModel").getProperty("/noOfTableRows"));
                var startIndex;
                var oIndex = data.length % noOfTableRows;
                if (oIndex === 0) {
                    startIndex = data.length - noOfTableRows;
                } else {
                    startIndex = data.length - oIndex;
                }  
                var newData = data.slice(startIndex);

                //To set Table Data
                that.fnSetTableData(newData, startIndex, data.length, Math.ceil(data.length / noOfTableRows));
            },

            //Sets the table data
            fnSetTableData: function (newData, startIndex, endIndex, page) {
                var that = this;
                that.getView().getModel("ProductsModel").setProperty("/tableData", newData);
                that.getView().getModel("ProductsModel").setProperty("/startIndex", startIndex);
                that.getView().getModel("ProductsModel").setProperty("/endIndex", endIndex);
                //Sets Current page count
                that.getView().getModel("ProductsModel").setProperty("/page", page);
                //To Enable the nav bottons
                that.fnNavButtonsEnable();
            },

            //sets navigations buttons enable
            fnNavButtonsEnable: function () {
                var that = this;
                var data = that.getView().getModel("ProductsModel").getProperty("/productsData");
                var startIndex = that.getView().getModel("ProductsModel").getProperty("/startIndex");
                var endIndex = that.getView().getModel("ProductsModel").getProperty("/endIndex");
                
                //Enable or disable next and last buttons
                if (data.length > endIndex + 1) {
                    that.getView().getModel("NavModel").setProperty("/nextPageBtnEnable", true);
                } else {
                    that.getView().getModel("NavModel").setProperty("/nextPageBtnEnable", false);
                }
                
                //Enable or disable first and previous buttons
                if (startIndex === 0) {
                    that.getView().getModel("NavModel").setProperty("/firstPageBtnEnable", false);
                } else {
                    that.getView().getModel("NavModel").setProperty("/firstPageBtnEnable", true);
                }
            }

 

Save and Run the application.

In the initial screen, you will see first (<<) and previous (<) buttons are disabled and current page is 1 in 4 pages.

Initial%20View

 

When you click on next (>) button, you will see all buttons are enabled and current page is 2 in 4 pages.

Second%20Page

 

When you click on last (>>) button, you will see next (>) and last (>>) buttons are disabled and current page is 4 in 4 pages.

 

That’s it!!!

Assigned Tags

      3 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Shai Sinai
      Shai Sinai

      Is there any special reason for not using the built-in growing setting of sap.m.Table?

      Author's profile photo mundru venkatesh
      mundru venkatesh
      Blog Post Author

      Yes, we can use growing setting of sap.m.Table. But, if there are some hundreds of records and we want to see last few records then without scrolling that much by single click we can see those records.

      Also if user seen all the records and noted some records and now user want to see those records again, it is difficult to search those records again in that many records in case of growing setting. But, in case of pagination, user can simply note the page number and can see those records again by going to that particular page.

       

       

      Author's profile photo Shai Sinai
      Shai Sinai

      Thanks for the explanation of the business use case.