Sometime we have requirement where we need to prompt user while changing lookup value if he really wants change that value or not, especially when we need to fire some business logic on change of lookup based on it’s value. We got this requirement where we need to delete all child records when specific lookup in parent entity is changed, so in order eliminate the possibilities to change lookup value by mistake, we implemented below logic
if (Xrm.Page.ui.getFormType() == 2) {
if (Xrm.Page.getAttribute(“lookupField”).getValue() != null) {
var LookupID = Xrm.Page.getAttribute(“lookupField”).getValue()[0].id;
var EntityID = Xrm.Page.data.entity.getId();
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();
var ODataPath = serverUrl + “/XRMServices/2011/OrganizationData.svc”;
var retrieveResult = new XMLHttpRequest();
retrieveResult.open(“GET”, ODataPath + “/EntityNameSet(guid'” + EntityID + “‘)”, false); //query entity based on it’s id
retrieveResult.setRequestHeader(“Accept”, “application/json”);
retrieveResult.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
retrieveResult.send();
if (retrieveResult.readyState == 4 /* complete */) {
if (retrieveResult.status == 200) {
var retrievedCard = this.parent.JSON.parse(retrieveResult.responseText).d;
//check if lookup value is different then existing lookup value in database
if (retrievedCard.lookupField != null) {
if (retrievedCard.lookupField.Id != LookupID) {
var Response = confirm(“Are you sure you want to change lookup value”); //prompt message
if (Response != true) {
//set lookup with last value
var lookup = new Object();
var lookupValue = new Array();
lookup.id = retrievedCard.lookupField.Id;
lookup.entityType = retrievedCard.lookupField.Id.EntityType;
lookup.name = retrievedCard.lookupField.Id.Name;
lookupValue[0] = lookup;
Xrm.Page.getAttribute(“lookupField”).setValue(lookupValue);
}
} } } }}}
Hope it will help somebody to implement similar kind of requirement.
Enjoy !!!