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).
Associate:
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>” +
“</fetch>”;
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.
Disassociate:
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);
Fetch:
var fetch =
“<fetch mapping=’logical’>” +
“<entity name=’contact’>” +
“<all-attributes />” +
“<filter>” +
“<condition attribute=’contactid’ operator=’eq’ value='” + contactId + “‘ />” +
“</filter>” +
“</entity>” +
“</fetch>”;
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
}
Delete:
var deleteResponse = XrmServiceToolkit.Soap.Delete(“contact”, contactId);
SetState:
var response = XrmServiceToolkit.Soap.SetState(“contact”, contactId, 1, 2);
QueryByAttribute:
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);