The new CRM WebApi changes has been great to work with. Using the Web API verbs makes things easy to understand and develop. I always love working with Web APIs.
While most of the verbs are easy to understand and use, associating and disassociating a lookup attribute on an entity has to be done in a special way.
Let’s take a look at how to do an association to a lookup or disassociate an existing lookup from an entity.
Associate a lookup
Consider an example, where you want to populate “account” on an opportunity that has the relationship name as “opportunity_parent_account” then the code would be as follows:
var association = { "@odata.id": Xrm.Page.context.getClientUrl() + "/api/data/v9.0/opportunities(BE0E0283-5BF2-E311-945F-6C3BE5A8DD64)" }; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", datatype: "json", url: Xrm.Page.context.getClientUrl() + "/api/data/v9.0/accounts(C8A19CDD-88DF-E311-B8E5-6C3BE5A8B200)/opportunity_parent_account/$ref", data: JSON.stringify(association), beforeSend: function(XMLHttpRequest) { XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0"); XMLHttpRequest.setRequestHeader("OData-Version", "4.0"); XMLHttpRequest.setRequestHeader("Accept", "application/json"); }, async: true, success: function(data, textStatus, xhr) { //Success - No Return Data - Do Something }, error: function(xhr, textStatus, errorThrown) { Xrm.Utility.alertDialog(textStatus + " " + errorThrown); } });
If you observe, ‘association’ variable has the id of the opportunity whereas the URL in the Web API request has id of the account. The URL also has the relationship name. Below image would clear things up (if still unclear).
Disassociate a lookup
Similar to how we associated account lookup on opportunity, let’s disassociate account lookup from opportunity. To do that below would be the code:
$.ajax({ type: "DELETE", contentType: "application/json; charset=utf-8", datatype: "json", url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(C8A19CDD-88DF-E311-B8E5-6C3BE5A8B200)/opportunity_parent_account(BE0E0283-5BF2-E311-945F-6C3BE5A8DD64)/$ref", beforeSend: function(XMLHttpRequest) { XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0"); XMLHttpRequest.setRequestHeader("OData-Version", "4.0"); XMLHttpRequest.setRequestHeader("Accept", "application/json"); }, async: true, success: function(data, textStatus, xhr) { //Success - No Return Data - Do Something }, error: function(xhr, textStatus, errorThrown) { Xrm.Utility.alertDialog(textStatus + " " + errorThrown); } });
In the disassociate request you do not need to supply any data and the type is ‘DELETE’. The URL will have id for account as well as opportunity; but opportunity id will be used in conjunction with the relationship name.
Below image is the demonstration of disassociating the account from opportunity.
Leave a comment if you have any questions.
Hey,
How can i associate multiple opportunities to account in single ajax cal?
LikeLike