Validate Inactive Customer Selection

Requirement

Let's say we want to validate customer selection in opportunity record and if user selected inactive record, we want to display them an error alert to select another customer.

Solution

We can implement this requirement using server side or client side code, in this article we are going to provide sample code for checking account status and throw alert in case of inactive customer selected. We can create a JavaScript web resource and can use the following code. We can call our CheckIfAccountIsInactive method on onchange of parentaccountid field in opportunity form.

  1. function CheckIfAccountIsInactive() {  
  2.     if (Xrm.Page.getAttribute("parentaccountid").getValue() != null) {  
  3.         var AccountID = Xrm.Page.getAttribute("parentaccountid").getValue()[0].id;  
  4.         var ClientURL = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc";  
  5.         var Filter = "/AccountSet?$filter=AccountId eq guid'" + AccountID + "'";  
  6.         var Req = new XMLHttpRequest();  
  7.         Req.open("GET", ClientURL + Filter, false);  
  8.         Req.setRequestHeader("Accept""application/json");  
  9.         Req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  10.         Req.send();  
  11.         if (Req.readyState == 4 /* complete */ ) {  
  12.             if (Req.status == 200) {  
  13.                 var retrieved = this.JSON.parse(Req.responseText).d;  
  14.                 var accountState = retrieved.results[0].StateCode.Value;  
  15.                 if (accountState == 1) {  
  16.                     alert("This Customer is Inactive, Please select another customer");  
  17.                     Xrm.Page.getAttribute("parentaccountid").setValue(null);  
  18.                     return;  
  19.                 }  
  20.             }  
  21.         }  
  22.     }  
  23. }  

Once we have published our changes, if we will try to select inactive account in opportunity record we will get an alert like the following:



Next Recommended Readings