Home

Thursday, September 14, 2017

Create related entities in one operation using webapi’s (Deep Insert)



The following request body posted to the Account entity set will create a total of four new entities in the context of creating an account.
·         A contact is created because it is defined as an object property of the single-valued navigation property primarycontactid.
·         An opportunity is created because it is defined as an object within an array that is set to the value of a collection-valued navigation property opportunity_customer_accounts.
·         A task is created because it is defined an object within an array that is set to the value of a collection-valued navigation property Opportunity_Tasks.
-----------------------------------------------------------------------------------------------------
// Request
POST [Organization URI]/api/data/v8.2/accounts HTTP/1.1
Content-Type: application/json; charset=utf-8
OData-MaxVersion: 4.0
OData-Version: 4.0
Accept: application/json
{
 "name": "Sample Account",
 "primarycontactid":
 {
     "firstname": "John",
     "lastname": "Smith"
 },
 "opportunity_customer_accounts":
 [
  {
      "name": "Opportunity associated to Sample Account",
      "Opportunity_Tasks":
      [
       { "subject": "Task associated to opportunity" }
      ]
  }
 ]
}

// Response
HTTP/1.1 204 No Content
OData-Version: 4.0
OData-EntityId: [Organization URI]/api/data/v8.2/accounts(newGuid)
------------------------------------------------------------------------------------------------------
function deepInsert() {

    var entityName = "accounts";
    var clientURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();

    req.open("POST", encodeURI(clientURL + "/api/data/v8.2/" + entityName, 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 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                alert("Records created");
            }
            else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };

    req.send(JSON.stringify(
        {
            name: "Sample Account",
            primarycontactid:
            {
                firstname: "John",
                lastname: "Smith"
            },
            opportunity_customer_accounts:
            [
             {
                 name: "Opportunity associated to Sample Account",
                 Opportunity_Tasks:
                 [
                  { subject: "Task associated to opportunity" }
                 ]
             }
            ]
        }));


}

No comments:

Post a Comment

Convert subgrid to Comments