Table sap.m.Table in SAPUI5

19
17607

[adsenseyu2]

Hello everyone, in this tutorial we will learn how to use tables in SAPUI5 applications or SAP Fiori Apps.In SAPUI5 UI elements library table can be found in two libraries one sap.m.Table and other sap.ui.table.Table. Both UI controls are used for creating tables in SAPUI5 application with subtle difference. As the namespace tells that sap.m.Table is used in developing mobile specific applications and sap.ui.table.Table is used in desktop specific applications. In this tutorials we will use sap.m.Table control to create a table and explores all possible features what it got for us. So lets get started.

1. Open Eclipse IDE and create a SAPUI5 Application project by clicking on File → New → Project. Choose Application Project under SAPUI5 Application Development.

New SAPUI5 Application Project2. Click on Next and provide the Project Name, choose sap.m library and hit Next to create a initial view.

Choose sap.m Library3. Provide the view name and choose type of the view as Java Script.Here you can choose any of the option as per your preference and hit Next to create project.

Create a New View4. A new SAPUI5 project is created in Project Explorer. Select index.html file in the project and double click to appear in the workbench window. Make sure the sap.m library is provided in this file to be able to use in the application.Code inside the index.html should like below.

Index.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />

<script src="resources/sap-ui-core.js" 
        id="sap-ui-bootstrap"
	  data-sap-ui-libs="sap.m"  
        data-sap-ui-theme="sap_bluecrystal">  
</script>
<!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->

<script>
  sap.ui.localResources("demotable");
  var app = new sap.m.App({
    initialPage: "iddemoTable1"
  });
  var page = sap.ui.view({
    id: "iddemoTable1",
    viewName: "demotable.demoTable",
    type: sap.ui.core.mvc.ViewType.JS
  });
  app.addPage(page);
  app.placeAt("content");
</script>

</head>
<body class="sapUiBody" role="application">
	<div id="content"></div>
</body>
</html>

5. Now double click on the demoTable.view.js to create and add Table inside the View. All the UI Element controls should be placed in the CreateContent() method of the view. Add the below code to create a Table and columns of the table in the view.

var oTable = new sap.m.Table("idPrdList", {   
      inset : true, 
      headerText : "List of Products",
      headerDesign : sap.m.ListHeaderDesign.Standard, 
      mode : sap.m.ListMode.None,   
      includeItemInSelection : false,   
    });
    
    var col1 = new sap.m.Column("col1",{header: new sap.m.Label({text:"Product Name"})});
    oTable.addColumn(col1); 
    
    var col2 = new sap.m.Column("col2",{header: new sap.m.Label({text:"Description"})});
    oTable.addColumn(col2); 
    
    var col3 = new sap.m.Column("col3",{header: new sap.m.Label({text:"Price"})});
    oTable.addColumn(col3);    

 

6. In the above step we have instantiated the Table and set the properties like “headerText” to the Table. After that we have added 3 columns Product Name, Description and Price to the Table. The full API reference for the table is available here.

[adsenseyu1]

7. After adding columns we need to have “ColumnListItem” as Aggregation to hold the data i.e different rows inside the table.So create the ColumnListItem and bind the aggregation to the table. Write the below code.

var colItems = new sap.m.ColumnListItem("colItems",{type:"Active"});
oTable.bindAggregation("items","/value",colItems);

 

8. After adding the ColumnListItem we need to define cells. Each cell can by of any basic Value Holders from the sap.m library. Here i have used sap.m.Text to display the data in Table as simple Text.Append the below code to the existing code.

var txtNAME = new sap.m.Text("txtNAME",{text:"{ProductID}"});
colItems.addCell(txtNAME); 
    
var txtNAME2 = new sap.m.Text("txtNAME2",{text:"{ProductName}"});
colItems.addCell(txtNAME2); 
   
var txtNAME3 = new sap.m.Text("txtNAME3",{text:"{UnitsInStock}"});
colItems.addCell(txtNAME3);

9. Now we have created a Table with 3 columns and ColumnListItem as aggregation to hold multiple rows. We need to add the Table to the View to be able to see in the UI. So add the instance of the Table to the content of the Page like below.

return new sap.m.Page({
		title: "Title",
		content: [
		            oTable
		]
	});

10. By this our designing of Table is done. Lets test the application and check whether we are able to see the Table in UI. You should see the Table like below.

Table Output11. Now table is empty our next step is to provide the data to this Table. To provide the data to the table we need to create JSON Model to set the data to the model. So Navigate to the controller demoTable.comtroller.js and write the below code inside the Init( ) method.

onInit: function() {
var sUrl = "http://services.odata.org/Northwind/Northwind.svc/Products";
var oModel = sap.ui.model.json.JSONModel(sUrl);
sap.ui.getCore().setModel(oModel);
}

 

12. What we have done in the above step. Declared a JSON model and set the data to the model by passing the Northwind OData service url of Product List. Next we have set the model to the core to access globally in the application. You can set the model to the View by writing this.getView().setModel(oModel).

13.  Save the project the test the application to running the index.html file. Right click in index.html → Run AsWeb App Preview. You should see the Table with data of products.

Final OutputYou have successfully created a table in SAPUI5 Application.In our next tutorials we will see what the different modes of Table available in sap.m.Table UI control.

Please stay tuned to us for more SAPUI5 Tutorials. Please feel free to comment and let us know your feedback. You feedback will keep us alive.

Thank you. 🙂

like-128

  • Luis Andres Lara Graffe

    Hi,

    I have a question about the step 12. Where do you have to set the model to the view? In the View Controller? Sorry if is a silly question, I’m just learning SAPUI5. I have done all the previous steps, but the table is not retrieving any data.

    Thanks:

    Luis Lara.

    • AdminSAPLearners

      Hi Luis,

      Thank you for your interest.
      You have to set the model in the view controller method onInit( ). Please see the step-11.

      Thanks,
      Admin

      • Luis Andres Lara Graffe

        Thanks for your quick answer.

        Yes, I have placed the following code on the view controller:

        onInit: function() {
        var sUrl = “http://services.odata.org/V3/Northwind/Northwind.svc/Products”;
        var oModel = sap.ui.model.json.JSONModel(sUrl);
        sap.ui.getCore().setModel(oModel);

        this.getView().setModel(oModel);

        }

        But I can not get the table populated with any value from the web service. The url is right as I tested it manually. I will upgrade my eclipse to Luna, could be that I’m working on the old Juno version?

        • AdminSAPLearners

          Hi Luis,

          Can you please try this OData Service – http://services.odata.org/Northwind/Northwind.svc/Products

          Thanks,
          Admin

          • Luis Andres Lara Graffe

            Yes, I try it, but is not working. I try it as well with https. Also, I’m using the Web Ide as well, because I though that the problem was probably for a wrong configuration of my Eclipse Luna or for a proxy blocking my machine, but with the Web Ide (that is in the cloud and shouldn’t have any problem to connect to a public web service) is not working.

            I tried the following urls:

            http://services.odata.org/Northwind/Northwind.svc/Products
            https://services.odata.org/Northwind/Northwind.svc/Products

            Server respond with status of 404 (Not Found).

            Best Regards:

            Luis Lara.

          • AdminSAPLearners

            Hi Luis,

            You can reach us to Skype Id : saplearners.hub
            If you want so.

            Thanks,
            Admin

          • AdminSAPLearners

            Hi Luis,

            Can you try this

            var sUrl = “proxy/http/services.odata.org/Northwind/Northwind.svc/Products”;
            var oModel = sap.ui.model.json.JSONModel(sUrl);

  • AbhieSpeaks

    Hi,

    One thing I am curious is there a way to add grouped, multi level header for columns? How can we achieve that in sap.m.Table control?

  • Subha
  • Shekar Mantri

    Hi when i am trying to do this tutorial i am getting the following error.Can you please help me to solve my issue.

  • Venkat Reddy

    Hi All,
    Thanks for sharing Good Post!!!
    I have done this without any errors….
    But I want to Implement Table scroll bar could you please tell me How to implement scroll bar on the table ?.. For Example Initial needs display first 5 rows on table then scroll down reaming rows are display ?

    Regards,
    venkat

    • AdminSAPLearners

      Hi Venkat,

      Thanks for your kind feedback. Glad that you were able to create. We will create an example for Table with scrolling soon.

      Thanks,
      Admin

  • Banupriya

    If I need only selected data from data services,I need to pass parameters along with the url rit?How can I do it?
    And How can I bind another data service(url) in the same controller with different model?

    • AdminSAPLearners

      Hello Bhanupriya,

      Thanks for your comments.

      You can pass parameters to the OData URL using Query Options.Please have a look this blog
      http://www.saplearners.com/filter-query-option-in-sap-netweaver-gateway/

      Thanks,
      Admin

      • Banupriya

        Hi,

        It was helpful.But I also need to know how can I bind two web services in a single controller .I have two web services in json format.I need to bind the filtered output from both the services in a single controller.

        When I tried to do so,Only one of the web service was called while another service was never hit.

        Thanks,

        Banu

        • AdminSAPLearners

          Hello Bhanupriya,

          You can declare two JSON Models like below with two different Urls.

          var sUrl_1 = “http://services.odata.org/Northwind/Northwind.svc/Products”;
          var oModel_1 = sap.ui.model.json.JSONModel(sUrl_1);

          var sUrl_2 = “http://services.odata.org/Northwind/Northwind.svc/Categories”;
          var oModel_2 = sap.ui.model.json.JSONModel(sUrl_2);

          You can reach us on skype – “saplearners.hub”

          Thanks,
          Admin

          • Banupriya

            Hello,

            Currently I dont have access to skype over here.It would be great if you help me out here.

            I have my code as below.when I comment out the second model and its controls ,the data is fetched from the first url and binded to the table.But when I tyr to run both the models together I dont get output for both.

            jQuery.sap.declare(“model.PlatformSettings”);

            jQuery.sap.declare(“model.StoreList”);

            sap.ui.controller(“homedepot.ims.view.ArticleOverview”, {

            /**

            * Called when a controller is instantiated and its View controls (if available) are already created.

            * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.

            * @memberOf app.view.ArticleOverview

            */

            url:”…/yjson_anon/alu/detailExt/1.0″,

            url2:”…/yjson_anon/alu/stock/1.1″,

            labelDataModel:null,

            labelForecastModel:null,

            onInit: function() {

            var oRouter = sap.ui.core.UIComponent.getRouterFor(this);

            oRouter.attachRoutePatternMatched(this.onRouteMatched,this);

            labelDataModel=new sap.ui.model.json.JSONModel({});

            labelDataModel.attachRequestCompleted(this.searchDataSuccess,this);

            this.getView().overviewPage.setModel(labelDataModel);

            labelDataModel.attachRequestFailed(this.searchDataFailed,this);

            sap.ui.getCore().setModel(labelDataModel,”labelDataModel”);

            /*var oRouter = sap.ui.core.UIComponent.getRouterFor(this);

            oRouter.attachRoutePatternMatched(this.routeMatchedEvent,this);

            labelForecastModel=new sap.ui.model.json.JSONModel({});

            labelForecastModel.attachRequestCompleted(this.searchDataSuccess1,this);

            this.getView().overviewPage.setModel(labelForecastModel);

            labelForecastModel.attachRequestFailed(this.searchDataFailed,this);

            //var article=sap.ui.getCore().getModel(“labelSearchModel”);

            sap.ui.getCore().setModel(labelForecastModel,”labelForecastModel”);*/

            },

            onRouteMatched:function(event)

            {

            if(event.getParameter(“name”)==”articleResults”){

            var article=sap.ui.getCore().getModel(“labelSearchModel”);

            var currentarticle =article.getProperty(“/articleNumber”);

            labelDataModel.loadData(this.url,

            {

            “article”:currentarticle ,

            “site”:7001

            }

            , false,”GET”,true);

            }

            },

            searchDataSuccess:function(event)

            {

            var data = event.getSource().getData();

            if(data.gw_message.type == “E”){

            sap.m.MessageToast.show(data.gw_message.message);

            }

            else

            {

            labelDataModel.setProperty(“/vendor”,labelDataModel.getProperty(“/vendor”));

            }

            },

            routeMatchedEvent:function(event)

            {

            if(event.getParameter(“name”)==”articleResults”){

            var article = sap.ui.getCore().getModel(“labelSearchModel”);

            var currentarticle =article.getProperty(“/articleNumber”);

            labelForecastModel.loadData(this.url2,

            {

            “article”:currentarticle ,

            “lookupSite”:7001,

            “local”:”X”,

            “site”:7001

            }

            , false,”GET”,true)

            }

            },

            searchDataSuccess1:function(evnt)

            {

            var data = evnt.getSource().getData();

            if(data.message.type == “E”){

            sap.m.MessageToast.show(data.message.message);

            }

            else

            {

            labelForecastModel.setProperty(“/stock”,labelForecastModel.getProperty(“/stock”));

            }

            },

            /**

            * Similar to onAfterRendering, but this hook is invoked before the controller’s View is re-rendered

            * (NOT before the first rendering! onInit() is used for that one!).

            * @memberOf app.view.ArticleOverview

            */

            // onBeforeRendering: function() {

            //

            // },

            /**

            * Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.

            * This hook is the same one that SAPUI5 controls get after being rendered.

            * @memberOf app.view.ArticleOverview

            */

            // onAfterRendering: function() {

            //

            // },

            /**

            * Called when the Controller is destroyed. Use this one to free resources and finalize activities.

            * @memberOf app.view.ArticleOverview

            */

            // onExit: function() {

            //

            // }

            });

      • Banupriya

        Hi,
        I have posted a question and I dint get any of the replies.Yours being a renowned forum,it would be great if you help me in sorting the issue asap. Thanks