Dynamics 365 v9.0: Xrm.WebApi – Operations Part – 2

By | February 5, 2018

Introduction:

In our previous blog, we have discussed about performing CURD operations Create, Update, Delete and Retrieve using Xrm.WebApi. In this blog, we will discuss Retrieve Multiple and Execute Actions.

Let’s explore about these operations one by one.

1. Retrieve Multiple: 

Retrieve multiple is used to retrieve more than one record from MS CRM. Suppose we want to retrieve all active contact from CRM then we will use the Retrieve multiple.

If we want to retrieve multiple records then use Xrm.WebApi.retrieveMultipleRecords

The parameters of this function are shown below.

  1. Entity logical name
  2. Odata Query (i.e. select and filter)
//this function is used to retrieve Account
function retrieveMultipleAccounts() {
    var queryOption = "";
    try {

        //create the query
        queryOption = "?$select=fullname,telephone1,preferredcontactmethodcode,createdon,_parentcustomerid_value,creditlimit&$filter=(statecode eq 0)";

        //execute the query and get the results
        Xrm.WebApi.retrieveMultipleRecords("contact", queryOption)
           .then(function (data) {
               retrieveContactSuccess(data.entities);
           },
               function (error) {
                   Xrm.Utility.alertDialog(error.message);
               };

    } catch (e) {
        Xrm.Utility.alertDialog(e.message);
    }
}

In retrieveContactSucess function loop through the records and get the values as shown below.

///retrieve success
function retrieveContactSuccess(results) {

    try {
        //get the values 
        $.each(results, function (index, data) {

            //string
            var fullname = data["fullname"];

            //lookup
            var customerGuid = data["_parentcustomerid_value"];
            var customerName = data["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"];
            var customerEntityLogicalName = data["_parentcustomerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

            //money
            var creditLimit = data["creditlimit@OData.Community.Display.V1.FormattedValue"];

            //date
            var createdonFormattedValue = data["createdon@OData.Community.Display.V1.FormattedValue"]; // gives date in following format 2017-09-30T21:10:19Z

            var createdon = data["createdon"]; // gives date in following format 10/1/2017 2:40 AM

            //optionset
            var preferredConMethod = data["preferredcontactmethodcode@OData.Community.Display.V1.FormattedValue"];
        });
    } catch (e) {
        Xrm.Utility.alertDialog(e.message);
    }
}

If you have more than 5000 records than used data.nextLink. And if the response has value data.nextLink then used it to retrieve next set of records.

2. Execute Action: 

There are predefined Actions defined in Dynamics CRM 2016 that can be executed using Web API. On the following link will find the list of Web API actions. https://msdn.microsoft.com/en-in/library/mt607829.aspx

There are three types of Action as listed below.

Unbound actions: It is not bound to any specific entity. i.e the first parameter to such actions does not include the entity. E.g. WinOpportunity, CancelContract etc

Bound actions: It is bound to a specific entity. i.e the first parameter to such actions does not include the entity. e.g. – AddToQueue Action

Custom action: It is custom actions developed by developers using Processes.

Now we will discuss about Qualify request. Suppose you want to qualify request programmatically then we will use Qualify request. Web API provides QualifyLead Action.

In our blog, we have explained QualifyLead using WebApi. Now we will see how we can do the same using inbuilt Xrm.WebApi.

To execute action use Xrm.WebApi.execute.

//This function is used to qualify lead
function qualifyLead() {
    var saleOrderID = null;
    var columnsSet = null;
    var salesOrderToInvoiceReq = null;
    var leadId = "E5975EA3-531C-E511-80D8-3863BB3CE2C8";
    var qualifyLeadReq = "";
    try {

        qualifyLeadReq = {
            entity: {
                id: leadId,
                entityType: "lead"
            },
            CreateAccount: true,
            CreateContact: true,
            CreateOpportunity: true,
            Status: 3,
            getMetadata: function () {
                var metadata = {
                    boundParameter: "entity",
                    parameterTypes: {
                        "entity": {
                            "typeName": "Microsoft.Dynamics.CRM.lead",
                            "structuralProperty": 5
                        },
                        "CreateAccount": {
                            "typeName": "Edm.Int32",
                            "structuralProperty": 1
                        },
                        "CreateContact": {
                            "typeName": "Edm.Int32",
                            "structuralProperty": 1
                        },
                        "CreateOpportunity": {
                            "typeName": "Edm.Int32",
                            "structuralProperty": 1
                        },
                        "Status": {
                            "typeName": "Edm.Int32",
                            "structuralProperty": 1
                        }
                    },
                    operationName: "QualifyLead",
                    operationType: 0
                };

                return metadata;
            }
        };

        Xrm.WebApi.execute(qualifyLeadReq)
            .then(function (result) {
                Xrm.Utility.alertDialog("Success");
            },
            function (error) {
                var message = error.message;
                //Add handling of error that occurred
            });
  } catch (e) {
Xrm.Utility.alertDialog(e.message);
    }

}

Conclusion:

Using Xrm.WebApi in Dynamics 365 v9.0, it is easy to perform CURD operation without performing AJAX request or creating own library or using third party libraries.

One Pic = 1000 words! Analyze data 90% faster with visualization apps!

Get optimum visualization of Dynamics 365 CRM data with –
Kanban Board – Visualize Dynamics 365 CRM data in Kanban view by categorizing entity records in lanes and rows as per their status, priority, etc.
Map My Relationships – Map My Relationships – Visualize connections and relationships between Dynamics 365 CRM entities or related records in a Mind Map view.

5 thoughts on “Dynamics 365 v9.0: Xrm.WebApi – Operations Part – 2

  1. Viswa

    Hi Inogic,

    I’m a good follower of your blogs. Thanks for your help for MS Buddies!!!

    Problem Statement:
    Recently I faced issue like, as part of Migration of Java Script. I have used the code which u have mentioned in the blog for “retrieveMultipleAccounts” in which u have mentioned “.fail(function (error) ” when Microsoft team has seen “.fail” method they have blasted us for using that syntax.

    As the syntax which u have given in this blog is working fine so we have used that syntax.
    Can u please tell us why we should not go with the “.fail” which you have mentioned? and this “.fail” is not using in the Microsoft blogs.

    will be waiting for your reply..!!!

    Thanks & Regards

    1. Inogic

      Hi,

      As we have used promise so we used .fail but it should not be there, we have changed the blog.

      Thanks!

  2. Vissu

    Not working through Unified Interface. getting error : Web Api failure in Dynamics CRM.
    but working fine in normal interface.
    Please suggest.

    Viswanath

    1. Inogic

      Please check If you get the Xrm object in UCI or not. If not then try with the parent.Xrm in UCI.

      Thanks!

Comments are closed.