Retrieve Multiple Records using Web API in Dynamics 365 version 9.0

Introduction:

In this blog article, we will be showing how use fetch XML to retrieve multiple records with the new Web API in Dynamics 365 version 9.0

Implementation:

Step 1: The retrieveMultipleRecords() method retrieves a collection of entity records.

The basic syntax is as follows:

Xrm.WebApi.retrieveMultipleRecords(entityLogicalName,options,maxPageSize).then(successCallback, errorCallback);

Here the options parameter refers to the query that will decide the data which has to be retrieved from the system. We will be using the fetchXml attribute  to specify a FetchXML query  to retrieve contacts of a specific account.

The maxPageSize indicates number of records to be returned per page. If this is not specified the default value is 5000. In this example we have not specified the maxPageSize.

Step 2:  First we write the code and upload it as a JavaScript web resource.

Code

var scripting = {
retrieveMultipleContacts(executioncontext) {
debugger;
var formContext = executioncontext.getFormContext();
var accountId = formContext.data.entity.getId();
var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='contact' ><attribute name='fullname' /><attribute name='telephone1' /><attribute name='contactid' /><order attribute='fullname' descending='false' /><filter type='and'><condition attribute='parentcustomerid' operator='eq' uitype='account' value ='" + accountId + "' /></filter></entity ></fetch > ";
Xrm.WebApi.retrieveMultipleRecords("contact", "fetchXml= " + fetchXml).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
console.log(result.entities[i]);
}
},
function (error) {
console.log(error.message);
}
);
}
};

Here we take the execution context as the input parameter and we get the form context using the getFormContext() method. This method returns a reference to the form or an item on the form.

Using the formContext we get get the account id which is used to fetch the contacts of that specific account.

Step 3: On the account form, in  the form properties we set the Event to OnSave as shown below.

Step 4: In the handler properties we set the function name, in our case it is scripting.retrieveMultipleContacts.

And it is important to check the “Pass execution context as the first parameter” checkbox as shown below.

Step 5: We see that the account A. Datum Corporation (sample) has two contacts.

Step 6:  The script runs when the form is saved and while debugging we can see in the console, two contacts are returned in the results. We get the the attributes that were present in the FetchXML query.

Hope this article was helpful!


Share Story :

SEARCH BLOGS :

FOLLOW CLOUDFRONTS BLOG :


Secured By miniOrange