Retrieve Multiple using OData in CRM 2011

Posted: May 31, 2012 in CRM 2011, Jscripts

The Open Data Protocol (OData) is an open web protocol for querying and updating data. It allows to query the datasource over the HTTP protocol and get the result back in formats like ATOM, JSON or plain XML, including pagination, ordering or filtering of the data.

To generate the OData queries you can get the crm2011 odata tool from the codeplex. This tool can be found at the below link.

http://crm2011odatatool.codeplex.com/

Retrieve Multiple using OData.

In my example, i’m gonna retrieve multiple related contact entities by selecting the account record in my custom entity.

To perform an ODATA call, we need to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

Here is my code,

 function Account_onchange() {
    var accountId = Xrm.Page.getAttribute("crm_accountid").getValue() != null ? Xrm.Page.getAttribute("crm_accountid").getValue()[0].id : null;
    if (accountId != null) {
        var contacts = GetContactsByAccount(accountId);
        if (contacts != null && contacts[0].results.length > 0) {
            for (var count = 0; count < contacts[0].results.length; count++) {
                alert(contacts[0].results[count].ContactId);
                alert(contacts[0].results[count].LastName);
            }
        }
    }
}

function GetContactsByAccount(accountId) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/ContactSet?$select=ContactId,LastName&$filter=ParentCustomerId/Id eq guid'" + accountId + "'";
    var jSonArray = new Array();

    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataUri,
        async: false,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.            
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data && data.d != null) {
                jSonArray.push(data.d);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error :  has occured during retrieval of the contacts");
        }
    });

    return jSonArray;
}

Retrieve Single record using OData.

In this example, i’m gonna retrieve AccountNumber, Telephone1 fields by passing Account Guid in the OData query.
Here is the example code,

 function Account_onchange() {
    var accountId = Xrm.Page.getAttribute("crm_accountid").getValue() != null ? Xrm.Page.getAttribute("crm_accountid").getValue()[0].id : null;
    if (accountId != null) {
        var account = GetAccountData(accountId);
        if (account != null && account[0] != null) {
            alert(account[0].AccountNumber);
            alert(account[0].Telephone1);
        }
    }
}

function GetAccountData(accountId) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/AccountSet(guid'" + accountId + "')?$select=AccountNumber,Telephone1";
    var jSonArray = new Array();

    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataUri,
        async: false,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.            
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data && data.d != null) {
                jSonArray.push(data.d);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error :  has occured during retrieval of the Account details");
        }
    });

    return jSonArray;
}

If you observe the above examples-
contacts[0].results is used to Retrieve Multiple records.
account[0] is used to Retrieve Single record.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s