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.
- function CheckIfAccountIsInactive() {
- if (Xrm.Page.getAttribute("parentaccountid").getValue() != null) {
- var AccountID = Xrm.Page.getAttribute("parentaccountid").getValue()[0].id;
- var ClientURL = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc";
- var Filter = "/AccountSet?$filter=AccountId eq guid'" + AccountID + "'";
- var Req = new XMLHttpRequest();
- Req.open("GET", ClientURL + Filter, false);
- Req.setRequestHeader("Accept", "application/json");
- Req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
- Req.send();
- if (Req.readyState == 4 ) {
- if (Req.status == 200) {
- var retrieved = this.JSON.parse(Req.responseText).d;
- var accountState = retrieved.results[0].StateCode.Value;
- if (accountState == 1) {
- alert("This Customer is Inactive, Please select another customer");
- Xrm.Page.getAttribute("parentaccountid").setValue(null);
- return;
- }
- }
- }
- }
- }
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: