Search code examples
sapui5

How to pass a key field as variable instead of hard-coded key value to OData operation?


I am calling the GetEntity OData read method from the SAP UI5 view controller and passing a key value in the request URL. I am getting the proper response from the back-end when I hardcode the key value.

However, when I try to pass the key value dynamically in a variable by appending it to the URL, it doesn't work. I get the following error

HTTP request failed 404

In below code, sGrant is the variable and it doesn't work. But if I replace the variable name with its value hard-coded in below code, for example, in the read method like this: "/GrantMasterSet('TY560003')", then it works:

var sGrant = this.byId("grantNbr").getValue();
var oMod = this.getOwnerComponent().getModel();
oMod.read("/GrantMasterSet('sGrant')", {
  success: function(oData) {
    var oJsonModel =  new JSONModel();
    oJsonModel.setData(oData);
    this.getView().setModel(oJsonModel);
  }.bind(this),
  error: function(oError) {
    MessageToast.show("Read Failed");
  }
});

Solution

  • You should concatenate the variable to the rest of the string, like this:

    oMod.read("/GrantMasterSet('" + sGrant + "')", {
    

    Or, you can use a template literal, which comes down to the same thing (notice the backtics):

    oMod.read(`/GrantMasterSet('${sGrant}')`, {