Code for Creating Charts in SAPUI5

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.ui.commons,sap.ui.table,sap.ui.ux3,sap.viz"
    data-sap-ui-theme="sap_goldreflection">
  </script>
  <!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
  <link rel="stylesheet" type="text/css" href="CSS/StyleSheet.css">
  <script>
  
  // **************************************************************************
  // Create the ux3 shell
  // **************************************************************************
  var oShell = new sap.ui.ux3.Shell({
  appTitle : "KPIs & Reports",
  showFeederTool : false,
  showInspectorTool : false,
  showSearchTool : false,
  showLogoutButton : false,
  worksetItems : [ new sap.ui.ux3.NavigationItem({
  text : "Chart Example"
  }) ]
  });
    sap.ui.localResources("Chart_demo");
    jQuery.sap.require("Chart_demo.global");
    var view = sap.ui.view({id:"idCharts1", viewName:"Chart_demo.Charts", type:sap.ui.core.mvc.ViewType.JS});
    
    // set the initial content of the Shell
    oShell.setContent(view);
    // place the Shell into the <div> element defined below
    oShell.placeAt("content");
  </script>

 </head>
 <body class="sapUiBody" role="application">
  <div id="content"></div>
 </body>
</html>
Chart.View.js
sap.ui.jsview("Chart_demo.Charts", {

 /** Specifies the Controller belonging to this View.
 * In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
 * @memberOf Chart_demo.Charts
 */
 getControllerName : function() {
  return "Chart_demo.Charts";
 },

 /** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.
 * Since the Controller is given to this method, its event handlers can be attached right away.
 * @memberOf Chart_demo.Charts
 */
 createContent : function(oController) {
  
  var oLayout = new sap.ui.commons.layout.MatrixLayout({
   id : "matrix1",
   layoutFixed : true,
   width : "1200px",
   columns:2,
   widths : [ "50%", "50%" ]
   });
  
  var oHeadLabel = new sap.ui.commons.Label({
   id : "HeadLB",
   text : " Sales Report on Country",
   width: "300px"
    
  });
  
  oHeadLabel.addStyleClass("furtherInfo");
  
  var oLabel = new sap.ui.commons.Label({
   id : "LB1",
   text : "Country",
   width: "100px"
    
  });
  
  oLabel.addStyleClass("country");
  
  // Create a ComboBox
  var oComboBox3 = new sap.ui.commons.ComboBox({
   id : "ComboBox3",
   width : "100px",
   change : function(oEvent) {
    oController.changeDropDown(oEvent.oSource.getSelectedKey());
   }
   
  });
  oComboBox3.addStyleClass("country");
  oCell = new sap.ui.commons.layout.MatrixLayoutCell({
//   colSpan : 3
  });  
  
  oCell.addContent(oLabel);
  oCell.addContent(oComboBox3);
  
  
  //Create an instance of the table control
  var oTable = new sap.ui.table.Table({
   title: " ",
   id:"oTable1",
   height : "400px",
   width:"600px",
   visibleRowCount: 5,
   //firstVisibleRow: 3,
   
  });
  
  oTable.addColumn(
    new sap.ui.table.Column({
     label: new sap.ui.commons.Label({text: "COUNTRY"}),
     template: new sap.ui.commons.TextField().bindProperty("value", "COUNTRY"),
     filterProperty:"COUNTRY",
     sortProperty: "COUNTRY"  
    }));
  
  oTable.addColumn(
    new sap.ui.table.Column({
     label: new sap.ui.commons.Label({text: "Year"}),
     template: new sap.ui.commons.TextField().bindProperty("value", "YEAR"),
     filterProperty:"YEAR" ,
     sortProperty: "YEAR"  
    }));
  
  oTable.addColumn(
    new sap.ui.table.Column({
     label: new sap.ui.commons.Label({text: "Sales"}),
     template: new sap.ui.commons.TextField().bindProperty("value", "SALES_COUNT"),
     filterProperty:"SALES_COUNT" ,
     sortProperty: "SALES_COUNT"  
    }));
  
  
  var oBarChart = new sap.viz.ui5.Bar({
//   width : "400%",
   height : "400px",
   width:"600px",
   id:"oBarChart1",
   visible : false,
   plotArea : {
   //'colorPalette' : d3.scale.category20().range()
   },
   title : {
    visible : true,
    text : 'Sales'
   },
   
  });
       
  var oPieChartObj = new sap.viz.ui5.Pie({
            id : "PieChart1",
            width: "600px",
            height: "400px",
            allDeSelectable: true,
            legendFirst: true,
            selectionMode: 'single',
            legendDirection: 'right',
            title: {
                visible: true,
                text: 'Sales'
            },
            titleHorizontalAlign: 'center',
           });
  
  var oLineChart = new sap.viz.ui5.Line({
            id : "LineChart1",
            width: "600px",
            height: "400px",
            allDeSelectable: true,
            legendFirst: true,
            selectionMode: 'single',
            legendDirection: 'right',
            title: {
                visible: true,
                text: 'Sales'
            },
            titleHorizontalAlign: 'center',
   
  });
  

  oLayout.createRow(oCell);  
  oLayout.createRow(oHeadLabel);
  oLayout.createRow(oTable);
  oLayout.createRow(oBarChart);
  oLayout.createRow(oPieChartObj);
  oLayout.createRow(oLineChart);

  return oLayout;
 

 }

});
Chart.Controller.js
sap.ui.controller("Chart_demo.Charts", {

/**
* 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 Chart_demo.Charts
*/
 onInit: function() {
  
  var oModel = new sap.ui.model.odata.ODataModel(
    serviceInitializer.serviceURI, true);
  serviceInitializer.serviceOModel = oModel;

 },

/**
* 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 Chart_demo.Charts
*/
 onBeforeRendering: function() {
  this.getCountryList();
 },

/**
* 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 Chart_demo.Charts
*/
// onAfterRendering: function() {
//
// },

/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* @memberOf Chart_demo.Charts
*/
// onExit: function() {
//
// }
 
 getCountryList: function(){
  var xthis = this;
  
  serviceInitializer.serviceOModel
  .read(
    "/CountrySet",
    null,
    null,
    false,
    function(oData, response) {
     countryListModel = new sap.ui.model.json.JSONModel();
     countryListModel.setData({
      result : oData.results
     }, true);

    }, function(error) {

    });  
  
  var data = [];
  var comboBoxField = sap.ui.getCore().byId("ComboBox3");
  var name;
  if (countryListModel != undefined ){
   
   for (var i = 0; i < countryListModel.oData.result.length;i++){
    data
    .push({
     "values" : countryListModel.oData.result[i].COUNTRY,
     "keys" : countryListModel.oData.result[i].COUNTRY,
     "VALUE_ID" : countryListModel.oData.result[i].COUNTRY
    });    
    
   }
   
   var oModel = new sap.ui.model.json.JSONModel();
   oModel.setData(data);
   comboBoxField.setModel(oModel);
   comboBoxField.bindAggregation("items", "/",
     new sap.ui.core.ListItem({
      text : "{values}",
      key : "{keys}"
     }));
   
   for (j=0; j < data.length; j++) {
    comboBoxField.setValue(data[0].values);
    countryName = data[0].values;
    break;
   }
 
    
  }  
  var setLabel = sap.ui.getCore().byId("HeadLB");
  if (countryName == 'IN'){
   setLabel.setText("Sales Report of India");
  }else if (countryName == 'DE'){
   setLabel.setText("Sales Report of Germany");
  }else if (countryName == 'US'){
   setLabel.setText("Sales Report of America");
  }
  
  xthis.changeDropDown(countryName);
 },
 
 changeDropDown: function(oText)  {
  
   //var xThis = this;
  //var textd = oEvent.getSource().getId();
  //var textd = "test"+oEvent;
  //alert(oEvent.getSource().getId() + " does it!");
  /*test_bb.myView.callView(textd);
   * */
   // xThis.createLayout(this);
  //this.getView().callView(textd);
  var setLabel = sap.ui.getCore().byId("HeadLB");
  if (oText == 'IN'){
   setLabel.setText("Sales Report of India");
  }else if (oText == 'DE'){
   setLabel.setText("Sales Report of Germany");
  }else if (oText == 'US'){
   setLabel.setText("Sales Report of America");
  }
  
      var allData;
   var oModel2 = new sap.ui.model.json.JSONModel();
   serviceInitializer.serviceOModel
     .read(
       "/CountrySet?$filter=COUNTRY eq '"+ oText +"'",
       null,
       null,
       false,
       function(oData, response) {
//        allData = oData.Status;
        oModel2.setData({
         allData : oData.results
        }, true);
       },
       function(error) {
       });   
   var year = [];
   var salesData = [];
   var temp;
   
   
   
   var oShowChart = new sap.ui.model.json.JSONModel({
    
    businessData : ( function() {
     var oData1 = [];
     for (var i = 0; i< oModel2.getData().allData.length; i++ ){
      
      oData1.push({
       
       Year: oModel2.getData().allData[i].YEAR,
       Sales:oModel2.getData().allData[i].SALES_COUNT
       
      });
      
     };
     return oData1;
    }())
   });
   
var oPieChart = new sap.ui.model.json.JSONModel({
    
    businessData : ( function() {
     var oData1 = [];
     for (var i = 0; i< oModel2.getData().allData.length; i++ ){
      
      oData1.push({
       
       Year: oModel2.getData().allData[i].YEAR,
       Sales:oModel2.getData().allData[i].SALES_COUNT
       
      });
      
     };
     return oData1;
    }())
   });

var oLineChart = new sap.ui.model.json.JSONModel({
 
 businessData : ( function() {
  var oData1 = [];
  for (var i = 0; i< oModel2.getData().allData.length; i++ ){
   
   oData1.push({
    
    Year: oModel2.getData().allData[i].YEAR,
    Sales:oModel2.getData().allData[i].SALES_COUNT
    
   });
   
  };
  return oData1;
 }())
});



     // A Dataset defines how the model data is mapped to the chart
  var oDataset = new sap.viz.ui5.data.FlattenedDataset({

   // a Bar Chart requires exactly one dimension (x-axis)
   dimensions : [
    {
     axis : 1, // must be one for the x-axis, 2 for y-axis
     name : 'Year',
     value : "{Year}"
    }
   ],

   // it can show multiple measures, each results in a new set of bars in a new color
   measures : [
       // measure 1
    {
     name : 'Sales', // 'name' is used as label in the Legend
     value : '{Sales}' // 'value' defines the binding for the displayed value  
    }
    
   ],
   
   // 'data' is used to bind the whole data collection that is to be displayed in the chart
   data : {
    path : "/businessData"
   }
   
  });
    // A Dataset defines how the model data is mapped to the chart
  var oDataset2 = new sap.viz.ui5.data.FlattenedDataset({

   // a Bar Chart requires exactly one dimension (x-axis)
   dimensions : [
    {
     axis : 1, // must be one for the x-axis, 2 for y-axis
     name : 'Year',
     value : "{Year}"
    }
   ],

   // it can show multiple measures, each results in a new set of bars in a new color
   measures : [
       // measure 1
    {
     name : 'Sales', // 'name' is used as label in the Legend
     value : '{Sales}' // 'value' defines the binding for the displayed value  
    }
    
   ],
   
   // 'data' is used to bind the whole data collection that is to be displayed in the chart
   data : {
    path : "/businessData"
   }
   
  });
  var oDataset3 = new sap.viz.ui5.data.FlattenedDataset({

   // a Bar Chart requires exactly one dimension (x-axis)
   dimensions : [
    {
     axis : 1, // must be one for the x-axis, 2 for y-axis
     name : 'Year',
     value : "{Year}"
    }
   ],

   // it can show multiple measures, each results in a new set of bars in a new color
   measures : [
       // measure 1
    {
     name : 'Sales', // 'name' is used as label in the Legend
     value : '{Sales}' // 'value' defines the binding for the displayed value  
    }
    
   ],
   
   // 'data' is used to bind the whole data collection that is to be displayed in the chart
   data : {
    path : "/businessData"
   }
   
  });  
  
  var oTableObj = sap.ui.getCore().byId("oTable1");
  //oTableObj.setData(allData);
  oTableObj.setModel(oModel2);
  oTableObj.bindRows("/allData");
    
  var oBarChartObj = sap.ui.getCore().byId("oBarChart1");
  oBarChartObj.setDataset(oDataset);
  oBarChartObj.setModel(oShowChart);
  
  var oPieChartObj = sap.ui.getCore().byId("PieChart1");
  oPieChartObj.setDataset(oDataset2);
  oPieChartObj.setModel(oPieChart);
  
  var oLineChartObj = sap.ui.getCore().byId("LineChart1");
  oLineChartObj.setDataset(oDataset3);
  oLineChartObj.setModel(oLineChart);
  
 } 

});

global.js
jQuery.sap.declare("pipo_demo.global");

var serviceInitializer = {
 serviceURI : "proxy/http/example.com:8022/sap/opu/odata/sap/ZSAN_COUNTRY_SRV",
 serviceOModel : null,
 serviceJSONModel : null
};

var countryListModel;
var countryName;

0 comments: