In our last article we provided sample code to write retrieve method using Web API. Retrieve methods brings data based on the primary key, so we just need to pass primary key of specific entity record whose data we want to bring and obviously it always returns a single record. In this post we are going to provide sample code for retrieving multiple resultset, where we can define query to bring specific data.
Let’s say we want to count number of child contacts records for specific parent account and want to show count on the parent account entity. We do have other options to do this but for our demo purpose let’s say we want to do that using JavaScript.
To write our query, we can use $filter with different operators to check any particular condition, for example in our case to count child contact records we need to query contact entity based on the account lookup present in contact entity. In Web API field of the entities are represented as properties, you can check properties for particular entity here. In contact entity type parent customer lookup represented as _accountid_value so we need to compare current account with this property like the following,
_accountid_value eq e6e7f801-23b3-4398-8ec2-18518a3f9d3d //where GUID represent parent account
Now to count the resultset, we can use $count in our query so directly we can get number of child record. We can create JavaScript web resource and use the following code under text editor:
- function retrieveentityCollection(entity, options) {
- var serverURL = Xrm.Page.context.getClientUrl();
- var Query = entity + options;
- var req = new XMLHttpRequest();
- req.open("GET", serverURL + "/api/data/v8.0/" + Query, true);
- req.setRequestHeader("Accept", "application/json");
- req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
- req.setRequestHeader("OData-MaxVersion", "4.0");
- req.setRequestHeader("OData-Version", "4.0");
- req.onreadystatechange = function() {
- if (this.readyState == 4 ) {
- req.onreadystatechange = null;
- if (this.status == 200) {
- var data = JSON.parse(this.response);
- if(data['@odata.count']!=null)
- Xrm.Page.getAttribute("numberofemployees").setValue(data['@odata.count']);
- } else {
- var error = JSON.parse(this.response).error;
- alert(error.message);
- }
- }
- };
- req.send();
- }
Now we can write the following method to use retrieveentityCollection method
Stay tuned for more Web API Samples!