Retrieve records with Fetchxml using Jscript – CRM 2011
Retrieve the records using FetchXML is a convenient way as we can form the FetchXML easily using the ‘Advanced Find’ .
Once you have the FetchXML ready, below is the JScript to execute and read the result set.
- In this sample, I am fetching records from custom entity “Bikes” which has relationship with ‘Contact’ entity. (i.e., Fetch all the bikes of a Contact whose full name contains ‘Raj’)
- Note – I am using “xrmservicetoolkit” helper Jscript which is available in CodePlex. You just need to download the Jscript and refer to your CRM form.
function getBikesByContactName() {
var fetchXml =
“<fetch mapping=’logical’>” +
“<entity name=’raj_bike’>” +
“<attribute name=’raj_name’ />” +
“<attribute name=’createdon’ />” +
“<link-entity name=’contact’ from=’contactid’ to=’raj_customerid’ alias=’ad‘>” +
“<attribute name=’fullname’ />” +
“<filter type=’and’>” +
“<condition attribute=’fullname’ operator=’like’ value=’%raj%’ />” +
“</filter>” +
“</link-entity>” +
“</entity>” +
“</fetch>”;
// Execute the fetch
var bikes = XrmServiceToolkit.Soap.Fetch(fetchXml);
// Get the results by loop through ‘bikes’
for (var indxBikes = 0; indxBikes < bikes.length; indxBikes++) {
alert(“Bike Name – “+bikes[indxBikes].attributes.raj_name.value);
alert(“Created On – “+bikes[indxBikes].attributes.createdon.value);
// Get the related entity (i.e., Contact) attributes using LinkEntity alias)
alert(“Related entity attribute (Contact Name) – ” + bikes[indxBikes].attributes.ad.fullname.value);
}
}
🙂
Thank you. I used this for a similar thing to get the Business Unit name of someone given their Full Name.
The trick is to change the alias in the link-alias tag of the Fetch query. When you download it gives a unique identifier. In my case, I changed it simply to “bu”.
The text value of the Business Unit came back in:
returnArray[0].attributes[“bu.name”].value
Thanks again.