Tuesday, March 6, 2018

MSCRM Javascript Retrieve Record Using WebAPI Request

Source Code:


function retrieveRecord() {
          var req = new XMLHttpRequest();
          req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts", true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
          req.setRequestHeader("OData-MaxVersion", "4.0");
          req.setRequestHeader("OData-Version", "4.0");
          req.onreadystatechange = function() {
          if (this.readyState == 4) {
              req.onreadystatechange = null;
              if (this.status == 204 || this.status == 200) {
                    //do something
                    var records = JSON.parse(this.response);
                    Xrm.Utility.alertDialog(records.value.length + " Record(s) retrieved successfully!");
              }
              else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send();
}

Re-usuable function:


//requestType = Type of Request("POST","GET","PATCH","DELETE").
//query = Your CRM Url + "/api/data/v8.2" + EntitySetName(ex: accounts).
//entityData = If you want to create/update record then send entityData else send null.
//successCallBack = this function will return the response data.
//errorCallBack = this function will return the error data.
//executionMode = asyncronous pass true for synchronous pass false.
function webApiRequest(requestType, query, entityData, successCallback, errorCallback, executionMode) {
        var req = new XMLHttpRequest();
        req.open(requestType, query, executionMode);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 204 || this.status === 200) {
                    var successData;
                    if (this.response != "") {
                        successData = JSON.parse(this.response);
                    }
                    else {
                        var projectUri = this.getResponseHeader("OData-EntityId");
                        successData = projectUri.substr(projectUri.length - 38).substring(1, 37);
                    }
                    successCallback(successData);
                } else {
                    errorCallback(this.statusText);
                }
            }
        };
        if (entityData != null && entityData != undefined && entityData != "")
            req.send(JSON.stringify(entityData));
        else
            req.send();
    };

Detail Information:

1) req.open("Request Type" , Request URL , executionMode(Sync, Async))

    Request Type: 

                     1) POST (To Create Record)
                     2) GET (To Retrieve/Retrieve Multiple Record(s))
                     3)PATCH (To update/status change of a record)
                     4)DELETE (To Delete Record)

    Request URL:

                     1) "Xrm.Page.context.getClientUrl()" is to get the current CRM Url
                     2) "/api/data/v8.2/accounts" ( In this "api/data/v8.2" is common for all webapi                              requests") v8.2 is the api version if you are using 2016 crm version then                                version will be 8.0/8.2  for D365 we will use v9.0
                     3)  "accounts" is an EntitySet name. Suppose if you want to find account                                     entityset name just frame URL like "Your CRM URL"/api/data/v8.2 and hit                               enter then you can find list of entities in your crm. Press control + F and                                 enter "account"(entityname) there you will find entitySet Name as below

     ExecutionMode:

                       1) Synchronous (false)
                       2) Asynchronous (true)

     Note: Must use Schema names for attribute data mapping.
               ex: new_name (Logical Name)
                     Name (Display Name)
                     new_Name (Schema Name) => This type should be used to create entityObj

No comments:

Post a Comment