Microsoft Dynamics CRM 2011

Microsoft Dynamics CRM 2011

Friday, December 20, 2019

Deep Insert Request for Account Entity using AJAX on Dynamics 365


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.The following is the source I used for this:

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/create-entity-web-api#bkmk_CreateRelated


var fnDeepInsert = () => {

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

    req.open("POST", encodeURI(clientURL + "/api/data/v9.1/" + 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  ) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                alert("No Content = Four Entities created using DEEP INSERT");
            }
            else {
                let error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };

    req.send(JSON.stringify(
        {
            name: "Account",
            primarycontactid:
            {
                firstname: "Bender",
                lastname: "Rodriguez"
            },
            opportunity_customer_accounts:
            [
             {
                 name: "Opportunity for Bender",
                 Opportunity_Tasks:
                 [
                  { subject: "Task related to Bender" }
                 ]
             }
            ]
        }));
}






2 comments: