Pages

Monday, June 18, 2012

Synchronous Retrieve Multiple Query

We have covered how to go about constructing retrieve queries for the following cases:

So we need to close out this topic by providing how to go about constructing a synchronous retrieve multiple query. Once again, synchronous queries are necesssary where there is jscript dependency logic.

So let's get right to it.

First of all place the following function into one of your form jscript resources:

function retrieveMultipleSync(entity,filter,fields) {

    try {
  var context = Xrm.Page.context;
  var serverUrl = context.getServerUrl();
  var query = new XMLHttpRequest();
  var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/" + entity + "Set"+fields+"&$filter="+filter;
  query.open('GET', oDataSelect, false);
  query.setRequestHeader("Accept", "application/json");
  query.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  query.send(null);
  return JSON.parse(query.responseText).d.results;
 } catch (e) {
  alert("Retrieve multiple failed to return results");
 }

}


The next step is to call the above function to retrieve the values you are looking for by passing the following parameters:
  • entity - the entity logical name e.g. Product, Contact, Account
  • filter - a valid filter clause which will retrieve 1 or more records from the entity (see example)
  • fields - you wish returned from the retrieve query. NB: These are case sensitive so be sure to ensure to check how they are defined on the entity. You also can use the OData Query tool to get the syntax. Errors encountered with configuring this are most likely to be in this area.  

The following is a sample call to the retrieveMultipleSync function:

 var entity = "new_contact_systemuser";
 var entityid = Xrm.Page.data.entity.getId();
 var filter = "contactid eq guid'" + entityid + "'" + " and "+  "systemuserid eq guid'" + Xrm.Page.context.getUserId() + "'";
 var fields = "?$select=systemuserid";
  
 var entityData = retrieveMultipleSync(entity,filter,fields);
 if (entityData.length > 0)
  return false;
 else 
  return true;

And that's a wrap!

No comments:

Post a Comment