Tuesday, March 6, 2018

MSCRM JavaScript Create Record Using WebAPI Request

       Source Code:

           var entityObj = {};
           entityObj["name"] = "TestAccount";

           //Other Data Types FYI. Must Use Attribute Schema names.
          //entityObj["new_name"] = "WebAPIUpdateProject"; //Single Line of Text
          //entityObj["new_projectdescription"] = "Test Update WebApi project"; //Multiple Line of Text
          //entityObj["new_contact@odata.bind"] = "/contacts(2123455D-BE62-E411-80D6-B4B52F567EC8)";  //Lookup
          //entityObj["new_existingproducts"] = 100000003; // Whole Number
          //entityObj["new_projecttype"] = true; // Two Options
          //entityObj["new_noofresources"] = 29.32; //Floating Point Number
          //entityObj["new_projectduration"] = new Date();
          //entityObj["new_percentagecompleted"] = 85.161245; //Decimal Number

          //entityObj["new_budget"] = 9582.50; // Currency
          

          var req = new XMLHttpRequest();
          req.open("POST",  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) {
                  var projectUri = this.getResponseHeader("OData-EntityId");
                  var ID = projectUri.substr(projectUri.length - 38).substring(1, 37); //newly created record 
                                guid.
                  Xrm.Utility.openEntityForm("account", ID); //Open newly created account record
                   Xrm.Utility.alertDialog("Record created successfully");
              } 
              else {
                  var error = JSON.parse(this.response).error;
                  Xrm.Utility.alertDialog(error.message);
              }
          }
      };
      req.send(JSON.stringify(entityObj));


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
         
                       

1 comment: