Using Xrm.WebApi in Dynamics 365/CRM

With the release of Dynamics 365 update 9.0, now we have a new library to implement WebApi methods using Xrm.WebApi. Instead of writing complete request, now we can just use direct CURD methods from WebApi.

If you are looking for how to write WebApi for Dynamics CRM 2016, check our sample index here

Xrm.WebApi have two properties to use for Online and Offline client. In this article we are going to implement a sample HTML webresource using Xrm.WebApi for online client.

Now to create entity record we can simply call Xrm.WebApi create method using following parameters:

function createAccount() {
    // collect account data
    var data = {
        "name": document.getElementById("txtname").value,
        "address1_city": document.getElementById("txtcity").value,
        "telephone1": document.getElementById("txtphone").value,
        "numberofemployees": document.getElementById("txttotalemployees").value,
        "websiteurl": document.getElementById("txtwebsite").value

    }
    // create account record
    parent.Xrm.WebApi.createRecord("account", data).then(
        function success(result) {
            document.getElementById("txtaccountid").value = result.id;
            alert("Account Created !!");
        },
        function(error) {
            alert(error.message);
        }
    );
}

Xrmapi1

To update entity record we can use following method and pass updated data:

function updateAccount() {
    // collect account data
    var data = {
        "name": document.getElementById("txtname").value,
        "address1_city": document.getElementById("txtcity").value,
        "telephone1": document.getElementById("txtphone").value,
        "numberofemployees": document.getElementById("txttotalemployees").value,
        "websiteurl": document.getElementById("txtwebsite").value

    }
    //get account id
    var accountId = document.getElementById("txtaccountid").value;

    // update account record
    parent.Xrm.WebApi.updateRecord("account", accountId, data).then(
        function success(result) {
            alert("Account Record Updated");

        },
        function(error) {
            alert(error.message);

        }
    );

}

Xrmapi2

And to delete we can simply pass entity and record it like following:

function deleteAccount() {
     var accountId = document.getElementById("txtaccountid").value;
     parent.Xrm.WebApi.deleteRecord("account", accountId).then(
         function success(result) {
             alert("Account deleted");

         },
         function(error) {
             alert(error.message);

         }
     );
 }

Xrmapi3

You can download complete code from GitHub here
Stay Tuned for more Dynamics 365 Update 9.0 features !!!

Leave a Reply

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