› Dynamics 365, Enterprise › Create and Associate records using Xrm.WebApi

Create and Associate records using Xrm.WebApi

Clinton D'Mello
Trainee Software Engineer
Published on December 30, 2017
Category: Dynamics 365, Enterprise

Introduction:

In this blog we will demonstrate how to create and associate records using Xrm.WebApi which provides methods to use Web Api to create and manage records.

Implementation:

Step 1: The syntax to create a new entity record is as follows:

Xrm.WebApi.createRecord(entityLogicalName,data).then(sucessCallback,errorCallback);

Here entityLogicalName(string) and data(object) parameters are required. The “data” parameter is a JSON object defining the attributes and values for the new record.

Step 2: In this example we will create a sample account record along with a primary contact for that account, associate an opportunity to the account and create task and notes for the opportunity all in a single operation. This type of process is called as a deep insert.

The code for the same is as shown below:

var scripting = {

recordCreation: function () {

var data = {

"name": "CRAYONS LTD.",

"description": "This Account is Created using a Web API",

"creditonhold": false,

"telephone1": "9954565154",

"address1_city": "Mumbai",

"primarycontactid": {

"firstname": "Clinton",

"lastname": "Dmello"

},

"opportunity_customer_accounts": [

{

"name": "Opportunity Associated to CRAYONS LTD.",

"Opportunity_Tasks": [

{ "subject": "Task Created" }

],

"Opportunity_Annotation": [

{

"subject": "Note Created",

}

]

}

]

}

Xrm.WebApi.createRecord("account", data).then(

function success(result) {

console.log("Account Created with ID" + result.id);

//perform operations on record creation

},

function (error) {

console.log(error.message);

}

);

}

};

Step 3: In order to associate to an existing record @odata.bind annotation can be used.

For Example: “primarycontactid@odata.bind”:”/contacts(GUID of the contact)”.

Screenshots
1. A New Account is created with the name “CRAYONS LTD” and in the primary contact file the primary contact is set with the name Clinton Dmello as set in the code.
New Account Created

2. Also an opportunity is associated to the account as shown below in the associated view.

Opportunity associate to Account created

3. In the opportunity we can see the newly created task in the activities and a note as shown below.

Note Created

Task Created

Hope this helped!



Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

Looking for a demo?

We will get back to you very soon!
We promise.

  • This field is for validation purposes and should be left unchanged.