Aug 6, 2014

Code Snippet: Retrieve data with oData query

Just though of sharing a code snippet on retrieving data via oData query.

RetrieveOfficeLocationsByAccount: function()
{
    var _serverUrl = Xrm.Page.context.getServerUrl();
    var _accountID = Xrm.Page.data.entity.getId();
    var _oDataEndpointUrl = _serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    var _offices = RetriveOfficesCollection(_oDataEndpointUrl, _accountID);

    if (_offices != null) 
    {
        alert(_offices.results.length);

        for (var j = 0; j < _offices.length; j++) 
        {
            if (_offices[j].new_Location != null) 
            {
                alert(_offices[j].new_Location.Value);
            }
        }
    }
}

RetriveOfficeCollection: function(_oDataEndpointUrl, _accountID) 
{
    var _offices = null;
    _oDataEndpointUrl += "new_officeSet?$select=new_name,new_Location&$filter=new_AccountId/Id eq (guid'" + _accountID + "')&$orderby=new_name";
    var service = getRequestObject();

    if (service != null) {
        service.open("GET", _oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null);

        var requestResults = eval('(' + service.responseText + ')').d;
        if (requestResults != null && requestResults.results.length > 0) {
            _offices = requestResults;
        }
    }
    return _offices;
}

getRequestObject: function () 
{
    if (window.XMLHttpRequest) 
    {
        return new window.XMLHttpRequest;
    }
    else 
    {
        try 
        {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) 
        {
            return null;
        }
    }
}

There are two important notes about this code.

If you build the query correctly, you should be able to browse through your browser and see the list of records. It’s always good to check your query this way before proceeding, which will save a lot of time.

Other one is a note of caution. If you check the field names in the code, you may realize they are the schema names! (You see capital letters!.. example: new_Location not new_location). Usually, we use Name (which is all low case in CRM 2011) in most of the codes including Plug-ins.