Sap ui5 Important Questions

 ************************** Index ******************************

1) Tile creation steps

2) T Code

3) Jquery read operation

4) External navigation( navigate one appli to other appli through launchpad )

5) Don’t allow combobox to edit

6) Remove 1st record & display remaining record(in array)

7) Bind data in table which is not in form of array

 

1.> For tile creation follow the following steps:-


LPD_CUST - Create Tile for Application and Alias

/n/UI2/SEMOBJ - Create Semantic Object

Launchpad Config URL - http://nwgwtgd.bss.dev.jio.com:8000/sap/bc/ui5_ui5/sap/arsrvc_upb_admn/main.html?saml2=disabled

                                                                                          Create Catalog, Create Tile (Assign Semantic Object), Target Map with System Alias

                                                                                              Create Group for the Tiles


PFCG - New Role ( Add Catalog and Group)

------------------------------------------------------------------

2.> Important TCode used in SAP logon


transaction code(t code)

/n/iwfnd/error_log --> to check error in sap logon

se09 --> to check TR details

se80 --> to check version wrt bsp name

se01 to check code in TR

se09 to release TR

se01 to display n release tr

se38 to create package and upload application


role ex:-  S:MO_CORPORATE_CREATE_LOCATION


----------------------------------------------------------------------------------------------------------------------

3.> Jquery read operation

jQuery.ajax({


    url:'/myreadSet',


    type:'GET',


    async:false,


    success:function(oData){


        //Consume data and process with logic


    },


    error:function(error){


        //Display the error


    }


});



4.> For external navigation, one application to some different application on tile


if(this.selectedIndex=="2")

{

    var navigationService = sap.ushell.Container.getService("CrossApplicationNavigation");

navigationService.toExternal({

target: {

semanticObject: "ZCAF_IOT_CREATE_SEM",

action: "Display"

}

}); 

}

-----------------------------------------------------------

5.> Don’t allow combobox to edit


that.servTeam.addEventDelegate({

         onAfterRendering: function() {

$(".sapMComboBoxInner.sapMComboBoxTextFieldInner.sapMInputBaseInner").attr("readonly",true);

         }

});

note- give class name which shown in brower element

that.servTeam is your control

------------------------------------------------------------

6.> remove 1 record in array and display remains


     var jsonProposalModel = new sap.ui.model.json.JSONModel(oData.results[0].PeriodicVerVoResNav);

      jsonProposalModel.oData.results.splice(0,1);

     var abc=jsonProposalModel

     oTable.setModel(abc);

-----------------------------------------------------------------


7.> bind in table odata record which not in result(not in array),single record from backend


no need to give items="{/}" in view

var tableModel = new sap.ui.model.json.JSONModel();

tableModel.setData(oData);

var temp=this.getView().byId("idAUTTable");

temp.setModel(tableModel);

this.getView().byId("idAUTTable").bindElement("/");

-----------------------------------------------------------------------------8.>##### set model for transfer data to next page using routing######


press:function(val){

var object=val.getSource().getBindingContext().getObject();

if(val.getSource().getTooltip()=="Display"){

  object.disp="X"; 

  }else{

  object.disp=""; 

  }

  sap.ui.getCore().setModel(object,"S3");

that.getRouter().navTo("S3");

},


9.>########## Create function in odata ##############

This data contain some field information

that.oModel.create("/SaveDetSet",data,{async: true,success: function(oData, oResponse) {

that.busyDialog.close();

var msg=oData.Message;

sap.m.MessageBox.show(msg, {

icon: sap.m.MessageBox.Icon.SUCCESS,

title: "Success",

actions: [sap.m.MessageBox.Action.OK],

onClose:function(){

if(key=="Info"){

that.clearFields(0);

}else{

that.clearFields(1);

}

}

});

      },

      error:function(oData, oResponse){

  that.busyDialog.close();

var obj = JSON.parse(oData.response.body);   //execute in case of call fail

var msg = obj.error.message.value;

sap.m.MessageBox.show(msg, {

icon: sap.m.MessageBox.Icon.ERROR,

title: "Error",

actions: [sap.m.MessageBox.Action.OK]

});   

      }

      });

------------------------------------------------------------

10.>############ control binding of table #############


 var Logtemplate = new sap.m.ColumnListItem({

cells: [

        new sap.m.Text({

text: "{Name}({Pernr})",

        }),

        new sap.m.Text({

text: "{path:'Begda',formatter:'com.ril.hcm.engagmntfrom.util.formatter.dateFormatDisplay'}",

        }),

        new sap.m.Text({

text: "{ReqText}",

        }),

        new sap.m.Text({

text: "{PosidTxt}",

        }),

        new sap.m.Text({

text: "{path:'ChDt',formatter:'com.ril.hcm.engagmntfrom.util.formatter.dateFormatDisplay'}",

        }),

        new sap.m.Text({

text: "{StatusText}",

        }),

        new  sap.m.HBox({

items:[

       new sap.m.Button({

   text:"",

   icon:"sap-icon://display",

   press:that_S2.handleEdit

       }),

       new sap.m.Button({

   text:"",

   icon:"sap-icon://edit",

   press:that_S2.handleEdit,

   enabled:"{path:'Status',formatter:'com.ril.hcm.engagmntfrom.util.formatter.visibleEditBtn'}"

       })

       ]

        })

        ]

});

  idTable.setModel(that_S2.TableData);  

idTable.bindAggregation("items", {

path: "/TableDataSet",

template: Logtemplate

});


10.>########### file upload control###########


upload.xml


<core:FragmentDefinition xmlns="sap.m"

xmlns:html="http://www.w3.org/1999/xhtml" xmlns:core="sap.ui.core"

xmlns:f="sap.ui.layout.form" xmlns:ca="sap.ca.ui">

<Dialog title="{i18n>CMS_FILE_ATTACH}" contentWidth="30%">

<content>

<ca:FileUpload acceptRequestHeader="application/json"

items="/dataitems"

uploadUrl="/sap/opu/odata/sap/ZHR_ESS_CMS_new_SRV/AttachmentSet"

encodeUrl="/sap/bc/ui2/encode_file" fileName="filename" url="url"

mimeType="mimeType" fileId="documentId" deleteFile="onDeleteFile"

uploadFile="onUploadFile" fileUploadFailed="onFileUploadFailed"

beforeUploadFile="onBeforeUploadFile" showNoData="true"

useEditControls="true" deleteEnabled="true" uploadEnabled="true"

renameEnabled="false" showAttachmentsLabelInEditMode="true">

</ca:FileUpload>

<Label text="" />

<Label text="" />

<Toolbar>

<content>

<Text text="{i18n>CMS_FILE_UPLOAD}" />

</content>

</Toolbar>

</content>

<beginButton>

<Button text="Ok" press="onDialogCloseUpload" />

</beginButton>

</Dialog></core:FragmentDefinition>

11.>########## message box actions ###########


var a = oEvent.getSource().getParent().getId().split("-");

var idx = a[a.length-1];

sap.m.MessageBox.confirm("Do you want to delete this task for Employee?", {

icon: sap.m.MessageBox.Icon.CONFIRM,

title: "Confirmation",

actions: [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],

onClose : function(oAction) { 

if ( oAction === sap.m.MessageBox.Action.YES ) 

{

var tableID = that6.getView().byId("id_complete");

var tabModel = tableID.getModel().getData().taskSet;

var empData = sap.ui.getCore().getModel("EmpData"); 

var compData = sap.ui.getCore().getModel("CompData");

});

------------------------------------------------------------------

12.>############# delete from backend ############


var model = this.getView().getModel();

var sPath ="AttachmentListSet('"+docId+"')";

model.remove(sPath, null,function(oData, oResponse) {


}, function(err) {

var message= JSON.parse(err.response.body).error.message.value;

sap.m.MessageBox.show(message,

sap.m.MessageBox.Icon.ERROR,

"Error");

});


13.>############# read operation ##########



this.oModel.read(path, {

async: false,          

success: function(oData,oresponse) {

var tableModel = new sap.ui.model.json.JSONModel();

tableModel.setData(oData.results);

var col = new sap.m.ColumnListItem({

type : "Navigation",

press : function(oEvent) {

var value = oEvent.getSource().getBindingContext().getProperty("ExtRefNo");

cells : [ 

new sap.m.Text({

text : "{Description}"

}),

new sap.m.Text({

text : "{EmployeeRes}"

}),

new sap.m.Text({

text : "{path : 'CreatedAt', formatter : 'com.ril.ServiceRequest.util.Formatter.Date2'}"

})

        ]

});

that.tblInbox.setModel(tableModel);

that.tblInbox.bindItems("/",col);

that.busy.close();

},

error: function(oError) {

//oBusy.close();

that.busy.close();

that.tblInbox.unbindItems();

var errmsg = JSON.parse(oError.response.body).error.message.value;

sap.m.MessageBox.show(errmsg, {

title: "Error",

icon:sap.m.MessageBox.Icon.ERROR

});

}

});


----------------------------------------------

14######### combobox not editable #############


that.servTeam.addEventDelegate({

         onAfterRendering: function() {

//(give the class name which shown in browser developer tool element section) $(".sapMComboBoxInner.sapMComboBoxTextFieldInner.sapMInputBaseInner").attr("readonly",true);

         }

});

-------------------------------------------------

15.>######## to get particular selected item from table #########


var ab=[];

var items=this.getView().byId("idreservetable").getSelectedItems();


for(var i=0;i<=items.length-1;i++)

{

var IMSIdata=items[i].getBindingContext().getObject().Imsi;

ab.push(IMSIdata);

}

var x=ab.toString();

var IMSI=x.replace(/,/g, " ");

--------------------------------------------------------

16.>####### Download selected data into CSV ########


 var attachpath="FileDownloadSet(IvObjectId='"+IMSI+"',IvDocNumber='',IvDocType='IMS')/$value";

        this.oModel.read(attachpath,null,null,true,function(oData,response){

        var url = response.requestUri;

         sap.m.URLHelper.redirect(url, true);

         oBusy.close();

          },function(oData, oResponse) {

                      var message=oData.response.body;

                      var messageValue=message.split(":")[5];

                      var msg=messageValue.substr(0,39);

                      oBusy.close();

                      sap.m.MessageBox.alert("oData Response: "+msg, {

                      icon  : sap.m.MessageBox.Icon.ERROR,

                      title : "Error",

                     actions: [sap.m.MessageBox.Action.OK],

                                         });

                                    });










17.>######### update operation #################

  that.oModel.update("/EmpContactDetSet('')", data, null,

function(value) {

sap.m.MessageToast.show("Successfully Updated", {

duration : 10000

});

success= true;

}, function(value) {


var message = $(value.response.body).find(

'message').first().text();

var message= JSON.parse(value.response.body).error.message.value;

sap.m.MessageBox.show(message,

sap.m.MessageBox.Icon.ERROR,

"Error");


});

        if(success){

       that.inputBind();

}

---------------------------------------


        that.oModel.update("/MaSegmentLimUpnav", updatepayload, null,

function(value) {

sap.m.MessageToast.show("Successfully Updated", {

duration : 10000

});

success= true;

}, function(value) {


var message = $(value.response.body).find(

'message').first().text();

var message= JSON.parse(value.response.body).error.message.value;

sap.m.MessageBox.show(message,

sap.m.MessageBox.Icon.ERROR,

"Error");


});

*/

----------------------------------------------------

18.>########## open fragment and set model ############



if (!that.addDialog) {

that.addDialog = sap.ui.xmlfragment("updateOperation.view.fragment.AddFragment",that);

that.getView().addDependent(that.addDialog);

}

sap.ui.getCore().byId("DP1").addEventDelegate({

onAfterRendering: function() {

$(".sapMDP >input ").attr("readonly", "readonly");

//$("#" + sap.ui.getCore().byId("DP1")).attr("readonly", "readonly");

}

}); 

that.addDialog.open();

sap.ui.getCore().byId("ID_STATE_SELECT").setValue(that.getView().byId("ID_SELECT").getSelectedItem().getText());

var ctcId = sap.ui.getCore().byId("ID_CTC_SELECT");

var sPath1 = "/MinWageDDSet?$filter=ImType eq 'C'" ;

that.oModel.read(sPath1, null, null, false, function(oData, oResponse) {

oData.results[0].Description="Select";

var ctcJson= new sap.ui.model.json.JSONModel({"CTCDataSet":oData.results});

ctcJson.setSizeLimit(oData.results.length);

ctcId.setModel(ctcJson, "ctcAlias");

},function(oData, oResponse) {

var obj = JSON.parse(oData.response.body);

var msg = obj.error.message.value;

that.messageDialog(msg);

});


----------------------------------------------------

19.>########## component.js ############


jQuery.sap.declare("com.ril.hcm.ess.MinWages.Component");

jQuery.sap.require("sap.ui.core.UIComponent");

jQuery.sap.require("com.ril.hcm.ess.MinWages.util.formatter");

jQuery.sap.require("com.ril.hcm.ess.MinWages.functions.commons");

jQuery.sap.require("sap.ui.core.routing.History");

jQuery.sap.require("sap.m.routing.RouteMatchedHandler");


sap.ui.core.UIComponent.extend("com.ril.hcm.ess.MinWages.Component", {

metadata : {

"name" : "zfullscreentest",

"version" : "1.1.0-SNAPSHOT",

"library" : "com.ril.hcm.ess.MinWages",

"includes" : ["css/style.css"],// to add external css

"dependencies" : {

"libs" : [ "sap.m", "sap.ui.layout" ],

"components" : []

},

"config" : {

resourceBundle : "i18n/messageBundle.properties",

serviceConfig : {

name: "ZICM_SCHEME_PARAMETERS_SRV_02",

//serviceUrl:""

serviceUrl: "../com.ril.hcm.ess.MinWages/proxy/sap/opu/odata/sap/ZERC_MINIMUM_WAGES_SRV/?saml2=disabled"

//serviceUrl: "/sap/opu/odata/sap/ZERC_MINIMUM_WAGES_SRV/"

}

},

routing : {

config : {

"viewType" : "XML",

"viewPath" : "com.ril.hcm.ess.MinWages.view",

"targetControl" : "fioriContent", 

"targetAggregation" : "pages", 

"clearTarget" : false

},

routes : [

          // -------------------Tiles -----------------------------       

          {

  pattern : "",

  name : "S1",

  view : "S1"

          },

          {

  pattern : "DisplayConnectivity/{entity}/{entity3}/{entity4}/{entity8}/{entity1}/{entity5}/{entity7}/{entity9}/{entityD}/{entityEdit}",

  name :"DisplayConnectivity",

  view : "DisplayConnectivity"

          },

          {

  pattern : "DisplayCreateDevice/{entity}/{entity3}/{entity4}/{entity8}/{entity1}/{entity5}/{entity7}/{entity9}/{entityD}",

  name :"DisplayCreateDevice",

  view : "DisplayCreateDevice"

          },


          ]

}

},

createContent : function() {

var oViewData = {

component : this

};


return sap.ui.view({

viewName : "com.ril.hcm.ess.MinWages.view.Main",

type : sap.ui.core.mvc.ViewType.XML,

viewData : oViewData

});

},

init : function() 

{

BusyD=new sap.m.BusyDialog({

text:"Fetching Data..."

});

sap.ui.core.UIComponent.prototype.init.apply(this, arguments);

var sRootPath = jQuery.sap.getModulePath("com.ril.hcm.ess.MinWages");

var oServiceConfig = this.getMetadata().getConfig().serviceConfig;

var sServiceUrl = oServiceConfig.serviceUrl;

var oModel=new sap.ui.model.odata.ODataModel(sServiceUrl,true);

this.setModel(oModel);

var mConfig = this.getMetadata().getConfig();

this._routeMatchedHandler = new sap.m.routing.RouteMatchedHandler(this.getRouter(), this._bRouterCloseDialogs);

this._initODataModel(sServiceUrl);

var i18nModel = new sap.ui.model.resource.ResourceModel({

bundleUrl : [ sRootPath, mConfig.resourceBundle ].join("/")

});

this.setModel(i18nModel, "i18n");

this.getRouter().initialize();



},


exit : function() {

this._routeMatchedHandler.destroy();

},

setRouterSetCloseDialogs : function(bCloseDialogs) {

this._bRouterCloseDialogs = bCloseDialogs;

if (this._routeMatchedHandler) {

this._routeMatchedHandler.setCloseDialogs(bCloseDialogs);

}

},


_initODataModel : function(sServiceUrl) {

jQuery.sap.require("com.ril.hcm.ess.MinWages.util.messages");

var oConfig = {

metadataUrlParams : {},

json : true,

// loadMetadataAsync : true,

defaultBindingMode :"TwoWay",

defaultCountMode: "Inline",

useBatch : false

};


}

});

--------------------------------------------

20.>######### navigate to external application #########


var navigationService = sap.ushell.Container.getService("CrossApplicationNavigation");

navigationService.toExternal({

target: {

semanticObject: "ZHR_ESS",// semantic obj which created in sap logon

action: "procconfirm"

},

// if there is any parameter to pass with this to target application

params: {

flag_app: AppFlag

}

}); 


21.>*************** deep entity and navigation **********************

Onclose:function(){

var tableDataCreate=[];// empty array to push input data to backend

for(var c=0; c<oTable.length;c++){

var obj={

KamBp:oTable[c].getBindingContext().getObject().Bp,

parentBp:oTable[c].getBindingContext().getObject().LocPartner

};

tableDataCreate.push(obj);

}

var payloadCreateCAF = { 

IvFlag:ivFlag,

IvAssign:"",

PartnerAssignDeassignCheckNav:tableDataCreate // PartnerAssignDeassignCheckNav= it is navigation where in this you are passing the input data

                            };    that.oDataModel.create("/PartnerAssignDeassignSet",payloadCreateCAF ,{async: true, success:function(oData,response){

     if(oData.EvFlag == "S"){

var sercIndex=sap.ui.getCore().byId("radioSelect").getSelectedIndex();

    if(sercIndex==0){

var oMsg=oData.EvMessage.split("/")[1];

sap.m.MessageToast.show(oMsg);

}else{

var oMsg=oData.EvMessage.split("/")[1];

sap.m.MessageToast.show(oMsg);

}


}else {

          sap.m.MessageBox.show(oData.EvMessage , {

                      icon: sap.m.MessageBox.Icon.WARNING,

                      title: "Error",

                      actions: [sap.m.MessageBox.Action.OK],

                      onClose: function(oAction) {

                      }    } ); }

},error:function(oError){

if(oError.response!==undefined){

var msgv= JSON.parse(oError.response.body).error.message.value;

sap.m.MessageBox.show( msgv, { title: ERROR",icon:sap.m.MessageBox.Icon.ERROR});

}else{

sap.m.MessageBox.show( "No data found", { title:"ERROR",icon:sap.m.MessageBox.Icon.ERROR});

} }});},



22.>******************** upload file *****************

var that = this;

var file=this.file;

var fileId=this.oView.byId("fileUploadId").getId();

var oFile=this.oView.byId("fileUploadId");

var slug;

var msg;

try {

//that.SiteBusy.open();

if (file) {

if(file.type =="application/vnd.ms-excel" ||file.type =="application/pdf"||

file.type=="image/jpeg" || file.type=="image/jpg"){

this._bUploading = true;

var a = com.KAM.util.Formatter.getServiceUrl(com.KAM.util.Formatter.CRM_Kam_Deasssign,true);

var f = {

headers : {

"X-Requested-With" : "XMLHttpRequest",

"Content-Type" : "application/atom+xml",

DataServiceVersion : "2.0",

"X-CSRF-Token" : "Fetch"

},

requestUri : a,

method : "GET" };

var oHeaders;

if(fileId.includes("fileUploadId")==true){

var lv_session=sessionStorage.getItem("SessionUniqueID");

msg="File Uploaded Successfully....";

docName="CSV";

slug = docName+"@"+lv_session;

}

var oRelTableDisp=this.getView().byId("idASTable");

var that=this; 

OData.request(f, function(data, oSuccess) {

if(oSuccess.statusText=="OK"){ // for calling extra payload

oURL="/MaCorpKamDataSet?$filter=IvSessionId eq '"+lv_session+"'";

that.oDataModel.read(oURL,null,null,true,function(oData, oResponse) {

var tableModel = new sap.ui.model.json.JSONModel();

tableModel.setData(oData);

oRelTableDisp.setModel(tableModel);

oRelTableDisp.setVisible(true);

});

}

this.oToken = oSuccess.headers['x-csrf-token'];

oHeaders = {

"x-csrf-token" : this.oToken,

"slug" : slug

};

var oURL = "/sap/opu/odata/sap/ZCRM_KAM_DEASSIGN_SRV/MaKamFileUploadSet"; 

//evfileuploadset";         

jQuery.ajax({

type: 'POST',

url: oURL,

headers: oHeaders,

cache: false,

contentType: file.type,

processData: false,

data: file,

dataType:"json",

success: function(data,oResponse){

if (oResponse!="success"){

sap.m.MessageBox.show(

message , { 

icon  : sap.m.MessageBox.Icon.ERROR,                        

title : "Error",

actions: [sap.m.MessageBox.Action.OK], });

oFile.setValue();

}else {

oFile.setValue();

sap.m.MessageToast.show("File Uploaded Successfully");  

}

},

error:function(data){

oFile.setValue();

sap.m.MessageToast.show("file upload failed");

}

});

});

}else {

this.getView().byId("fileUploadId").setValue();

}

}

} catch(oException) {

oFile.setValue();

jQuery.sap.log.error("File upload failed:\n" + oException.message);}


23.>***********************To generate session***************************

onInit: function() {

    sessionStorage.SessionUniqueID = null;

    var session = sessionStorage.getItem("SessionUniqueID");

    this.generateUUIDSession(); 

  },

  generateUUIDSession:function(){

      if(sessionStorage.getItem("SessionUniqueID")=== "null"){

        var d = new Date().getTime();

        if(window.performance && typeof window.performance.now === "function"){

          d += performance.now(); //use high-precision timer if available

        }

var uuidSession = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {

          var r = (d + Math.random()*16)%16 | 0;

          d = Math.floor(d/16);

          return (c=='x' ? r : (r&0x3|0x8)).toString(16);

        });

        this.setDataSession(uuidSession);

              }  },

  setDataSession:function(uuidSession){

      sessionStorage.setItem("SessionUniqueID",uuidSession);

  },



24.>************************ to clear / delete session**************************

var sessionId = sessionStorage.getItem("SessionUniqueID");

this.delpath = "/SessionClearSet(Session='"+sessionId+"')";


25.>*****************to open launchpad using tcode*********************

/flpd_cust


26.> *********************to clear gateway cache**********************

/UI2/INVALIDATE_GLOBAL_CACHES - Select Execution mode 

/UI2/CHIP_SYNCHRONIZE_CACHE

/UI2/DELETE_CACHE_AFTER_IMP

/UI2/INVALIDATE_CLIENT_CACHES - Select For All users

/ui5/app_index_calculate

/UI5/UPDATE_CACHEBUSTER


27.> *******************************model in sapui5************************************

>odata 

> json

> xml

> resource


28.> ***************************** views in sapui5*************************

> xml

> javascript

> json

> html


29.> ***************************routing class******************************

sap.ui.core.routing

Router.routing class


30.> **********************How can pass data between view***********************


Using routing mechanism

This.navTo(“s1”,{

Ename:name,

Esal:sal

})




Then in component.js in pattern section

pattern : "InspDetail/{Ename}/{Esal}",

  name : "InspDetail",

  view : "InspDetail"

   },


Then we will get this passed data in second view  handlerout function

if (evt.getParameter("name")==="InspDetail"){

oevent.getParameter("arguments").Ename;

oevent.getParameter("arguments").Esal;

}


Another way is using component name

sap.ui.controller("com.ZMA_SITE_INSP.view.InspDetail")

in the above line com.ZMA_SITE_INSP is our component name

now if you want to passdata to entire application then

com.ZMA_SITE_INSP.ename=”pratik”;


in your entire application you will get ename ‘pratik’ by using com.ZMA_SITE_INSP.ename



31.>  what is application enhancement ?

 do some extra changes into your standard app

Like add extra property into your control



32.> How  to pass array from one view to another (pass more data)

 using json.stringyfy method

In the 1st view do like this

var ob=[];

ob=[{

ename:101,esal:1000

},

{

ename:102,esal:2000

}];

var x=JSON.stringify(ob);

this.getRouter().navTo("InspDetail",

{ejson:x});


in 2nd view 

var x=evt.getParameter("arguments").ejson;

var o=JSON.parse(x);


33.> how to pass table to backend

    Using array with payload given by backend team



34.>  design pattern in sapui5


MasterDetail

Master-Master-Detail

FullScreen

Full Screen-Full Screen-MasterDetail (Multi Flow)



35.>  Ajax call


jQuery.ajax({

method:”GET”,

url:”www.google.com”,

success:function(data){

var oModel=new sap.ui.model.json.JSONModel(data);

this.getView().setModel(oModel);

},

error:function(error){

console.log(error)

}

})

------------------------------------------------------------------------



36.> apply top 50 on odata before setting model to view


// that.oModel.read("/ZshdCustomerAcctgrpSet", {

// urlParameters: {

// "$top": 50

// },

// success: function (oData, response) {

// // qtb.cipi.cust.customerManagement.that._oDialog.open();


// var oJson = new sap.ui.model.json.JSONModel(oData);

// // oJson.setSizeLimit(50);

// sap.ui.getCore().byId("tableSelectID").setModel(oJson);


// sap.ui.core.BusyIndicator.hide();

// },


// error: function (oError) {


// var message = oError.message;

// sap.m.MessageBox.success(message, {

// title: "Error",

// initialFocus: null

// });

// }


// });


------------------------------------------------------------------------


37.> apply filter while read call and set limit to model


var ocustFilter = new sap.ui.model.Filter("CustomerNo", sap.ui.model.FilterOperator.Contains, "");

var oCustNameFilter = new sap.ui.model.Filter("Name", sap.ui.model.FilterOperator.Contains, "");

var oCompCodeFilter = new sap.ui.model.Filter("CompanyCode", sap.ui.model.FilterOperator.Contains, "");

var oChannelFilter = new sap.ui.model.Filter("DistrChannel", sap.ui.model.FilterOperator.Contains, "");

var oCountryFilter = new sap.ui.model.Filter("Country", sap.ui.model.FilterOperator.Contains, "");

var oCityFilter = new sap.ui.model.Filter("City", sap.ui.model.FilterOperator.Contains, "");

var oIndicatorFilter = new sap.ui.model.Filter("FavIndicator", sap.ui.model.FilterOperator.Contains, "X");

this.oModel = this.getOwnerComponent().getModel();

this.oModel.read("/BookMarkSet", {

filters: [ocustFilter, oCustNameFilter, oCompCodeFilter, oChannelFilter, oCountryFilter, oCityFilter, oIndicatorFilter],

urlParameters: {

"$top": 50

},

success: function (oResponse) {

this.getView().setBusy(false);

this.onSearchBindTable(oResponse);

// this.onPressCustomerDisplay(oResponse);

}.bind(this),

error: function (oError) {

this.getView().setBusy(false);

}.bind(this)

});


--------------------------------------------------------------

38.> Create and Open dialog using controller coding


this.getOwnerComponent().getModel().read("/CompanyCodeF4Set", {

success: function (data) {


var oJson = new sap.ui.model.json.JSONModel(data);

qtb.cipi.cust.customerManagement.that.oDialogCompCode.setModel(oJson);

var template = new sap.m.StandardListItem("", {

title: "{CompanyCode}",

description: "{Text}"

});

qtb.cipi.cust.customerManagement.that.oDialogCompCode.bindAggregation("items", "/results", template);

qtb.cipi.cust.customerManagement.that.oDialogCompCode.setTitle("Company Code");

qtb.cipi.cust.customerManagement.that.oDialogCompCode.open();


},


------------------------------------------------------------------

39.> set selected value of fragment to view 


var oTitle = oEvent.getSource().mProperties.title;

var oSelectedItem1 = oEvent.getParameter("selectedItem").mProperties;

if (oTitle === "Company Code") {

qtb.cipi.cust.customerManagement.that.oDialogCompCode = undefined;


if (oSelectedItem1) {

this.oSaleOrg.setValue(oSelectedItem1.title + " " + oSelectedItem1.description);

}

}


------------------------------------------------------------------

40.> apply filter at view level


var oSerTitle = oEvent.getSource().mProperties.title;

var aFilters = [];

var sQuery = oEvent.getParameter('value');

if (oSerTitle === "Company Code") {

if (sQuery && sQuery.length > 0) {

var filter = new sap.ui.model.Filter("CompanyCode", sap.ui.model.FilterOperator.Contains, sQuery);

aFilters.push(filter);

}

qtb.cipi.cust.customerManagement.that.oDialogCompCode.getBinding('items').filter(aFilters);

}


------------------------------------------------------------------

41.> Navigate from one page to another page


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

oRouter.navTo("RouteS1", true);


---------------------------------------------------------------------------

42.> Get the binding path of selected line item and get the binding


var oCon = oEvent.getSource().getBindingContext().getPath();

this.oContent = oEvent.getSource().getModel().getProperty(oCon);

-------------------------------------------------------------------------------

43.> Get binding of line item and set model at view level and access it to entire app


var oCon = oEvent.getSource().getBindingContext().getPath();

this.oContent = oEvent.getSource().getModel().getProperty(oCon);

var oVall = this.oContent.PartnerFunText;

var a = [];

a.push(this.oContent);

var odisJson = new sap.ui.model.json.JSONModel(a);

this.getOwnerComponent().setModel(odisJson, "disJSON");

----------------------------------------------------------------------------------

44.> Convert date into seconds


this.msaEndDate = this.getView().byId("idMSAEndEdit");

this.endDate = new Date(this.msaEndDate.getValue()).getTime() / 1000;


------------------------------------------------------------------------------------

45.> Create call of odata from ui


this.OModel.create("/CustGeneralDataSet", payload, {


success: function (oData, response) {

// var that = this;

sap.m.MessageBox.success("Changes has been Submitted Successfully", {

title: "Success",

initialFocus: null,

actions: [sap.m.MessageBox.Action.OK],

onClose: function (oAction) {

if (oAction === "OK") {

qtb.cipi.cust.customerManagement.that.onCloseChange();

var oRouter = sap.ui.core.UIComponent.getRouterFor(qtb.cipi.cust.customerManagement.that);

oRouter.navTo("RouteS1", true);

}

}

});


},


error: function (oError) {


var message = oError.message;

sap.m.MessageBox.success(message, {

title: "Error",

initialFocus: null

});

}


});

------------------------------------------------------------------------------


46.> URL: /sap/opu/odata/sap/ZSD_CIPI_CUSTOMER_MASTER_SRV/CustGeneralDataSet?$filter=AccountGrp eq 'Z006' and Customer eq '0000100003' and SalesOrg eq '1001' and Channel eq '70' &$expand=CustGenDataToCp,CustGenDataToPartner&$format=json

If URL contain expand then read call will become


var oAccGrpFilter = new Filter("AccountGrp", FilterOperator.EQ, accGrp);

var oCustFilter = new Filter("Customer", FilterOperator.EQ, cust);

var oSaleOrgFilter = new Filter("SalesOrg", FilterOperator.EQ, saleOrg);

var oChannelFilter = new Filter("Channel", FilterOperator.EQ, channel);


this.getOwnerComponent().getModel().read("/CustGeneralDataSet", {

filters: [oAccGrpFilter, oCustFilter, oSaleOrgFilter, oChannelFilter],

urlParameters: {

"$expand": "CustGenDataToCp,CustGenDataToPartner"

},

success: function (oResponse) { },

error:function(e){ }

});

---------------------------------------------------------------------

47.> If from backend we got 10 records and from them you have to find out duplicate record with there index then


var oText = [];

// calculate length of backend data

var dataLen = oResponse.results[0].CustGenDataToPartner.results.length;

for (var i = 0; i < dataLen; i++) {

//storing backend record in oText and sort duplicate on partnerfuntext

var partnerText = oResponse.results[0].CustGenDataToPartner.results[i].PartnerFunText; oText.push(partnerText);


}

var map = {};


for (i = 0; i < oText.length; i++) {

var element = oText[i]; 

// arr[i] is the element in the array at position i


// if we haven't seen the element yet, 

// we have to create a new entry in the map

if (!map[element]) {

map[element] = [i];

} else {

// otherwise append to the existing array

map[element].push(i);

}

// the whole if - else statement can be shortened to

(map[element] || (map[element] = [])).push(i)

--------------------------------------------------------------------

48.> Bind above sorted data to multiple simple form


if (oText.includes("Sold-to party") === true) {

//array of all simple form

var soldCustID = [oSoldCust, oSoldCust2, oSoldCust3, oSoldCust4, oSoldCust5];

for (i = 0; i < map["Sold-to party"].length; i++) {

if (soldCustID[i].getModel().getData() === null) {

var oIndex = map["Sold-to party"][i];

soldCustID[i].setModel(oModel);

soldCustID[i].bindElement("/results/0/CustGenDataToPartner/results/" + oIndex);

soldCustID[i].setVisible(true);

}


}

}

--------------------------------------------------------------------------

49.> Make combobox non editable


var that = this;

// take combobox here with id

this.clientSignC = this.getView().byId("idSignReq");

this.clientSignC.addEventDelegate({

onAfterRendering: function () {

that.clientSignC.$().find("input").attr("readonly", true);

}

});

-------------------------------------------------------------------------

50.> oRouter.navTo("viewName",true) what is use of true


when we use true then it will not keep history of navigation.



51> why xml views?

Mostly XML views are used in SAPUI5 developments rather than JavaScript views because:

1. To protect MVC (Model-View-Controller) guidelines: If a developer uses JavaScript views, then there is chance of putting processing code in the view itself, which violates the MVC principle.

2. As XML is not a programming language, there is no way you can put processing logic inside XML views. So, in that case, you will always use controller to put your processing logic following MVC architecture.

3. XML is the industry standard to put views in a UI based application.

4. The SAP Web IDE includes a WYSIWYG(What you see is what you get) graphical layout editor that works only with XML views.

5. Using XML views, you can use Layout Editor means Editor that allows you to easily drag and drop UI controls on the screen/page and it’s ready-made code will get available automatically to you.

6. Parsing of XML in devices is faster than JavaScript.

7. XML views are more attractive when compared to JS based view.

8. SAP ships all Fiori apps using XML views. So, as a SAPUI5 developer, better to have atleast the knowledge in how to read XML based views also along with JS views.

9. SAP recommendation is to use XML views instead of JS, as it is better in terms of maintainability and readability.

10. You can easily find out the structure and hierarchy of UI controls that are laid out within each other.


==============================================================================

Formatter :


datetimeformatter:function(ChangeDate){

var dateFormat = sap.ui.core.format.DateFormat.getDateInstance({pattern : "MMM dd,YYYY" })

              

               return dateFormat.format(ChangeDate);

},

<firstStatus>

<ObjectStatus active="true"      text="{path:'StartDate',formatter: '.datetimeformatter'}-{path:'EndDate',formatter: '.datetimeformatter'}"  width="100%"/>

</firstStatus>



Post a Comment

Previous Post Next Post