Dataverse – Display Error Message When Entry Already Exists

A few times I saw the requirement to display the error/warning message when the entry already exists in a model-driven app or Dynamics 365 CE/CRM.

Use Case / Requirement

For example, Assume You have an account form and have single-line text to enter some value. When the user input some value then the system should verify existing data or rows and display the error message.

Offen user asks the question of whether a display message is possible using the business rule. The answer is No.

So what are the options?

Possible Solution(s)

Option 1: 

Write Javascript which fires onchange of the control. Javascript is capable to check the existing data and display the error message.

Option 2:

Write Pre-Validation Plugin to verify and show popup or form notification when data exists. This action will happen when you save the form.

In my opinion, option 1 is the right approach for business and usability

Setup

  • Create new web resource for Javascript say Account.js
  • Copy the below code and update the above new file
  • Call the “verifyAccountNumber” method from onchange event of Account Number
function verifyAccountNumber(executionContext) {
    var formContext = executionContext.getFormContext();
    var accountNumber = formContext.getAttribute("accountnumber").getValue();
    var uniqueId="028d0060-bb07-4d9e-ab2e-080a18f1e8ec";

    try {
        var query = "accounts?$select=name,accountnumber&$filter=(accountnumber eq '" + accountNumber + "')";
        //Create a request
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/" + query, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.send();

        if(req.readyState == 4)
        {
            //Success 
            if (req.status == 200) {                
                var results = JSON.parse(req.response);
                var recordCount = results.value.length;
                if (recordCount > 0) {
                    alert("Account Number Already Exists");
                    formContext.ui.setFormNotification('Account Number Already Exists', 'WARNING', uniqueId);
                }
            }
            //Failure
            else {
                alert("Error: " + req.responseText);
            }
        }

    } catch (e) {
        Xrm.Utility.alertDialog(e);
    }
}

Call the method

  • Add the reference file that you created above
  • Set the function name

 

Outputs

1. Regular Alert

2. Form Notification

Happy Learning!

Please reach me if any Questions

 

3 comments

Leave a Reply

Your email address will not be published. Required fields are marked *