Everyone who wants to work with views in Dynamics Crm needs to be familiarized with FetchXml. It is the language that is used very commonly when retrieving filtered data in Dynamics Crm. One of the properties/fields when retrieving a savedquery or userquery records is the FetchXml one. This field in these two cases holds a definition for a view, defining attributes and conditions specific to that particular view. Let’s get started with building our own FetchXml definition from scratch.

For this post, account entity will be used as an example. We’re going to begin with creating the FetchXml document using jQuery’s parseXML function which will gives us xml document to work with:

var xmlDoc = $.parseXML(‘<fetch mapping=“logical“><entity name=“account“ /> </fetch>’),

$xml = $( xmlDoc );

After we have created the xml document using jQuery’s parseXML, we can then think of our filters. We can basically do two things inside FetchXml query:

  • Specify attributes we would like to be returned
  • Give conditions on attributes (based on their data types)

That can be achieved using the following line:

$xml.find(“entity”).append(“<attribute name=’name’/>”);

All that we have to specify in this attribute node is the name of the atribute (logical name). If we however don’t specify any attribute then all of them will be returned by the query.

Condition node has three node attributes: attribute (entity attribute), operator and value. Let’s say that we need to retrieve all account records whose names are equal to Contoso. That would be achived with the following condition:

$xml.find(“entity”).append(“<condition attribute=’name’ operator=’eq’ value=’Contoso’ />”);

There is one more thing that we will definitely need when working with these queries, and that is the need to group/ungroup conditions. The node I am talking about is the filter. It has only one attribute – type. This attribute tells the condition group which logical operator to use. It can have two values: AND and OR.

$xml.find(“condition”).wrapAll(“<filter type=’and’> </filter>”);

 

After we have our xml document we will just extract the FetchXml string which is the outer text of the Fetch node in this newly generated xml document. We do that in the following way:

var finalFetchXmlString = $(xml)[0].documentElement.outerHTML;

After we have the string we will pass it as a parameter to the function Fetch contained in the library I like to use when using SOAP service provided by Dynamics Crm.

var Records = XrmServiceToolkit.Soap.Fetch(finalFetchXmlString);

If you have done everything as explained in this post, you will have all the records from account entity whose names are equal to Contoso.