Development, Howto

Microsoft Dynamics 365 v9.0: Usage of new OOB WebApi functions – Part 1

It was anounced earlier that wrapper for usage of WebApi will be available as a part of v9.0 release. Now v9.0 is released so it became possible to check what can it do and what we can do with it.

Here is the list of methods available under Xrm.WebApi:

  • createRecord
  • updateRecord
  • deleteRecord
  • retrieveRecord
  • retrieveMultipleRecords
  • execute
  • executeMultiple

All methods return Promise object.

Examples:

createRecord method accepts 2 parameters – entity schema name and data of object to create:

var newRecord = {
    name: "Name of new account"
};

Xrm.WebApi.createRecord("account", newRecord)
    .then(function(result) {
        var newRecordId = result.id;
        //Handle scenario when record is created successfully
    })
    .fail(function (error) {
        var message = error.message;
        //Add handling of error that occurred
    });

updateRecord method accepts 3 parameters – entity schema name, id of record and data of object to update:

var updatedRecord = {
    name: "Updated Name of account"
};

Xrm.WebApi.updateRecord("account", "1cf84331-5ea9-e711-a94e-000d3a109280", updatedRecord)
    .then(function (result) {
        //Handle scenario when record was updated
    })
    .fail(function (error) {
        var message = error.message;
        //Add handling of error that occurred
    });

deleteRecord method accepts 2 parameters – entity schema name and id of record to delete:

Xrm.WebApi.deleteRecord("account", "1cf84331-5ea9-e711-a94e-000d3a109280")
    .then(function (result) {
        //Handle scenario when record was deleted =
    })
    .fail(function(error) {
        var message = error.message;
        //Add handling of error that occurred
    });

retrieveRecord method accepts 3 parameters – entity schema name, id of record and optional “options” parameter that includes $select, $expand and other options you want to use in retrieve statement.

*Note you don’t need to add anything to get Formatted Values of lookups or optionsets – it is done by default:

Xrm.WebApi.retrieveRecord("account", "AF2A3A01-5EA9-E711-A94E-000D3A109280", "$select=name,_ownerid_value")
    .then(function(result) {
        var accountname = result["name"];
        var ownerid = result["_ownerid_value"];
        var owneridname = result["_ownerid_value@OData.Community.Display.V1.FormattedValue"];
        var owneridtype = result["_ownerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
        //Handle retrieved data
    })
    .fail(function(error) {
        var message = error.message;
        //Add handling of error that occurred
    });

retrieveMultipleRecords method accepts 3 parameters – entity schema name, optional “options” parameter (with query you want to use to retrieve data) and optional “maxPageSize” parameter that defines number of records per page returned with response (you can check detailed explanation here):

Xrm.WebApi.retrieveMultipleRecords("account", "$select=name,_ownerid_value&$filter=name eq 'test'", 1)
    .then(function(result) {
        var records = result.entities;
        var nextPageUrl = result.nextLink;
        //Handle retrieved data
    })
    .fail(function(error) {
        var message = error.message;
        //Add handling of error that occurred
    });

I will describe execute and executeMultiple methods in following posts:

Microsoft Dynamics 365 v9.0: Usage of new OOB WebApi functions – Part 2

Microsoft Dynamics 365 v9.0: Usage of new OOB WebApi functions – Part 3

12 Comments

  1. Xrm.WebApi.retrieveRecord(…”$select=name,_ownerid_value”)
    Xrm.WebApi.retrieveMultipleRecords(…”$select=name,_ownerid_value&$filter=name eq ‘test'”..)
    There is a awful OData style… If I write something similar I’ll change params to individual parts:
    – [‘name’, ‘ownerid’]
    – [‘name’, ‘ownerid’], “and”, [‘name’, ‘eq’, ‘test’]

    1. I agree that style is not the best one but at the end you get plain url with additional payload based on the type of operation.

  2. HI Andrii

    thanks for the great article. Helped a lot.

    What I don’t get to work:
    promise chaining with multiple Xrm.WebAPI calls. If one of my results is empty, I would like to quit out of the chain.
    Yet that is not possible. I have tried Promise.reject with catch or reject handlers, also throwing an exception does not seem to work. The catch is never reached. Any ideas?

    Xrm.WebApi.retrieveRecord(“incident”, value[0].id, “$select=someattr”)
    .then(function (incident) {
    if (!incident || incident[“someattr”] === null) {
    throw new Error(‘stop’); //does not work
    Promise.reject(“StopHere”); //does not work either, it returns in the success callback of the next .then.
    }

    var someAttrVal = incident[“someattr”];
    return Xrm.WebApi.retrieveMultipleRecords(“queue”, “$select=emailaddress,name&$filter=someattr2 eq ” + someAttrVal + ” and emailaddress ne null”);
    })
    .then(function (results) {
    if (!results|| results.entities === null || results.entities[0] === null) {
    _setValue(executionContext);
    return;
    }
    _doSomething();
    }, function (rej) { debugger; })
    .catch(function(c) { debugger; })
    .fail(function (error) {
    var message = error.message;
    alert(message);
    });

  3. Hi Andrii,
    I used code snippet to create a new record in a cutom HTML Page but getting below exception. “Unable to get property ‘account’ of undefined or null reference” I have my changes on D365 online. I have http://../../ClientGlobalContext.js.aspx in my HTML page. Am I missing something? Please help!!

  4. error while posting code but its a basic HTML page with create call. Can you please add any working file that you have or used to this blog for reference? Thanks in advance Andrew!!

  5. Hello Andrii,

    Is there a reason you are using var in the scripts as opposed to let? I’ve been trying to improve my javascript knowledge and a lot of references are saying to use let as opposed to var. Being those are general jscript references and not specific to D365 jscripting I was curious if there is a reason I see a lot of D365 scripts using var still.

    Thanks!

    1. Scott,
      IE9+ is still supported browser (and believe me or not but it is used by customers) and let will not work there. So… I use var because of cross-browser compatibility.
      Andrew

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.