Tuesday, March 6, 2018

MSCRM JavaScript Delete Record Using WebAPI Request

Source Code:


function deleteRecord() {
          var serverUrl = Xrm.Page.context.getClientUrl();
          var req = new XMLHttpRequest();
          req.open("DELETE", serverUrl  + "/api/data/v8.2/accounts(D7F0BEBA-EBDF-E711-A94E-000D3AF0396C)", false);
          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) {
                    Xrm.Utility.alertDialog("Record deleted successfully!");
              } else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      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
              If you are using this code in html page use parent.Xrm.Page instead of Xrm.Page

No comments:

Post a Comment