XrmServiceToolKit – Associate, Disassociate, Fetch, etc

Well, sometimes we need to do some code in Javascript instead of Plugins C#.

So here is a way to Associate a relationship, in my case it was a N:N between quote and opportunity.

First of all I will search if the relation already exists and after I’ll create the relation (if doesn’t exists).


var fetch =
“<fetch mapping=’logical’>” +
“<entity name=’RelationshipName’>” +
“<all-attributes />” +
“<filter>” +
“<condition attribute=’opportunityid’ operator=’eq’ value='” + opportunityId + “‘ />” +
“<condition attribute=’quoteid’ operator=’eq’ value='” + quoteId + “‘ />” +
“</filter>” +
“</entity>” +

var retrieve = XrmServiceToolkit.Soap.Fetch(fetch);
if (retrieve.length == 0)
var quote = new XrmServiceToolkit.Soap.BusinessEntity(“quote”, quoteId);
var relatedQuotes = new Array();
relatedQuotes[0] = quote;
var response = XrmServiceToolkit.Soap.Associate(“RelationshipName”, “opportunity”, opportunityId, “quote”, relatedQuotes);

The same logic can be applied for the Disassociate, search for the record first to see if exists, and if exists (retrieve.length > 0) disassoaciate it.


var account = new XrmServiceToolkit.Soap.BusinessEntity(“account”, accountId);
var relatedAccounts = new Array();
relatedAccounts[0] = account;
var response = XrmServiceToolkit.Soap.Disassociate(“RelationshipName”, “contact”, contactId, “account”, relatedAccounts);


var fetch =
“<fetch mapping=’logical’>” +
“<entity name=’contact’>” +
“<all-attributes />” +
“<filter>” +
“<condition attribute=’contactid’ operator=’eq’ value='” + contactId + “‘ />” +
“</filter>” +
“</entity>” +

var retrieve = XrmServiceToolkit.Soap.Fetch(fetch);

if(retrieve.length > 0)


var contactName = retrieve[0].attributes.fullname.value; //String

var account = retrieve[0].attributes.accountid.id //Lookup



var deleteResponse = XrmServiceToolkit.Soap.Delete(“contact”, contactId);


var response = XrmServiceToolkit.Soap.SetState(“contact”, contactId, 1, 2);


I prefer to query with fetch.

var queryOptions = {
entityName: “contact”,
attributes: [“firstname”, “middlename”, “lastname”],
values: [“John”, “<&>”, “Snow”],
columnSet: [“firstname”, “lastname”, “middlename”, “familystatuscode”, “ownerid”, “creditlimit”, “birthdate”, “donotemail”, “donotphone”],
orderby: [“firstname”, “lastname”] // Order by firstname and then lastname even though we are only getting one record back

var fetchedContacts = XrmServiceToolkit.Soap.QueryByAttribute(queryOptions);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s