Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Duplicate Detection Using JavaScript

Posted on by 210

Hi, I'm trying to validate the mobile number with existing home phone for any leads in CRM and home phone with existing mobile for any leads in CRM.

if it is valid, I should throw an duplicate detection error with fullname of the duplicate lead. Instead of the count, I need to get the fullname value from the result set and display in the alert message

I'm new to Dynamics CRM development and java script. I need some help in this. 

function CaptureMiRequirements_onSave(eventArgs) {
    var mobile = Xrm.Page.getAttribute("mobilephone");
    var email = Xrm.Page.getAttribute("emailaddress1");
    var mainPhone = Xrm.Page.getAttribute("telephone1");

    var isNull = mobile.getValue() == null && email.getValue() == null && mainPhone.getValue() == null;
    var isBlank = mainPhone.getValue() == "" && mobile.getValue() == "" && email.getValue() == "";
    var notificationMessage = "Error";

    if (isNull || isBlank) {
        Xrm.Page.ui.setFormNotification("To save this record, please enter either an Email address, Main Phone or Mobile number.", "ERROR", notificationMessage);
        eventArgs.preventDefault();
        eventArgs.returnValue = false;
    }
    else {
        Xrm.Page.ui.clearFormNotification(notificationMessage);
    }
   
   
    if (mainPhone.getValue() != null || mobile.getValue() != null)
    {
      
       var mainphonevalue= Xrm.Page.getAttribute("telephone1").getValue();
      
       var mobilevalue=Xrm.Page.getAttribute("mobilephone").getValue();

       var context = Xrm.Page.context;

       var serverUrl = context.getClientUrl();

       var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

       var retrieveResult = new XMLHttpRequest();

       retrieveResult.open("GET", ODataPath +"/LeadSet?$select=FullName&$filter=(telephone1 eq mobilevalue or mobilephone eq mainphonevalue)",false);

       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 retrieved = this.parent.JSON.parse(retrieveResult.responseText).d;

               var Result = retrieved.results;

               if (typeof Result !== "undefined")

               {

                   var count = Result.length;

                   if (count>1)

                   {

                       alert("duplicate value not allowed");

                       executionObj.getEventArgs().preventDefault();

                   }

               }

           }


       }
    
    }
}

*This post is locked for comments

  • Suganthar_Satkunam Profile Picture
    Suganthar_Satkunam 210 on at
    RE: Duplicate Detection Using JavaScript

    Hi Clement, 

    Finally, I have corrected the WS call from CRM and checked the response using the Internet Explorer 'F12' Tool. I got the repose code as 200 (OK) but I have not got any result set. See the screenshot below

    3276.2.PNG

    Actually I have tested the service call, There is a data exists for that

    3276.2.PNG

    My Updated the JS script fucntion is as below

    function CaptureRequirements_onSave(eventArgs) {
    var mobile = Xrm.Page.getAttribute("mobilephone");
    var email = Xrm.Page.getAttribute("emailaddress1");
    var mainPhone = Xrm.Page.getAttribute("telephone1");

    var isNull = mobile.getValue() == null && email.getValue() == null && mainPhone.getValue() == null;
    var isBlank = mainPhone.getValue() == "" && mobile.getValue() == "" && email.getValue() == "";
    var notificationMessage = "Error";

    if (isNull || isBlank) {
    Xrm.Page.ui.setFormNotification("To save this record, please enter either an Email address, Main Phone or Mobile number.", "ERROR", notificationMessage);
    eventArgs.preventDefault();
    eventArgs.returnValue = false;
    }
    else {
    Xrm.Page.ui.clearFormNotification(notificationMessage);
    }


    if (mainPhone.getValue() != null || mobile.getValue() != null)
    {

    var mainphonevalue= mainPhone.getValue();

    var mobilevalue=mobile.getValue();

    var context = Xrm.Page.context;

    var serverUrl = context.getClientUrl();

    var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

    var retrieveResult = new XMLHttpRequest();

    alert(mobilevalue);
    debugger;
    retrieveResult.open("GET", ODataPath +"/LeadSet?$select=FullName&$filter=(Telephone1 eq '+mobilevalue+')",false);
    retrieveResult.setRequestHeader("Accept", "application/json");
    retrieveResult.setRequestHeader("Content-Type", "application/json; charset=utf-8?");
    retrieveResult.send();
    debugger;
    if (retrieveResult.readyState == 4 /* complete */)
    {
    if (retrieveResult.status == 200)
    {
    var retrieved = this.parent.JSON.parse(retrieveResult.responseText).d;
    var Result = retrieved.results;
    if (typeof Result !== "undefined")
    {
    for (var i = 0; i < Result.length; i++) {
    alert(Result[i].FullName);
    }
    var count = Result.length;
    if (count>1)
    {
    alert("duplicate value not allowed");
    executionObj.getEventArgs().preventDefault();
    }
    }
    }

    }


    /*Xrm.Page.ui.setFormNotification(ODataPath, "ERROR", notificationMessage);
    eventArgs.preventDefault();
    eventArgs.returnValue = false;*/

    }
    }

    I really do not know why i do not get any result set when i was checking through the debugging mode? Can you please shed some light ? or please let me know what other steps to dig the cause of the issue in Dynamics CRM.

  • Suganthar_Satkunam Profile Picture
    Suganthar_Satkunam 210 on at
    RE: Duplicate Detection Using JavaScript

    Thanks Andrew. I will use it for future Rest API call builds

  • Verified answer
    a33ik Profile Picture
    a33ik 84,323 Most Valuable Professional on at
    RE: Duplicate Detection Using JavaScript

    Hello,

    Isn't it easier to build queries using CrmRest builder - github.com/.../2.5.0.0

  • Verified answer
    Clem Profile Picture
    Clem 2,541 on at
    RE: Duplicate Detection Using JavaScript

    Make sure you have the correct uppercases on the Telephone1 field.

    The Soap endpoint requires you to pay attention to this and doens't accept the "all lowercases"

    here just replace "telephone1" by "Telephone1"

    Clément

  • Suganthar_Satkunam Profile Picture
    Suganthar_Satkunam 210 on at
    RE: Duplicate Detection Using JavaScript

    Hi Clement, Thanks for the answer, I tried the first point as below in internet explorer.

    https://YouCRMOrg//XRMServices/2011/OrganizationData.svc/LeadSet?$select=FullName&$filter=FullName eq 'Test Lead'

    Suga111.PNG

    So I got the result as below picture. click the link below for picture

    Then I tried the below

    https://YouCRMOrg//XRMServices/2011/OrganizationData.svc/LeadSet?$select=FullName&$filter=telephone1 eq '0292999956'

    I did not get any results. I have just changes the filter condition from Fullname to telephone1. There is no changes made. my send call did not return any data. but actually data exists in CRM for the second criteria.

    Please help me why it is not retrieving any data when there is a data exists in CRM

  • Clem Profile Picture
    Clem 2,541 on at
    RE: Duplicate Detection Using JavaScript

    Hi,

    Two points you can check to debug :

    * Do you have multiple results when you directly call the link :  http://YouCRMOrg/LeadSet?$select=FullName&$filter=(telephone1 eq "XXXXXX" or mobilephone eq "XXXX") ?

    if not, make sure the query is fixed first

    * Can you try using the developer tools of your favorite browser (F12) to check if you actually go into the " if (retrieveResult.status == 200)" part of code and if so, what do you have in the variable Result.

    Regards,

    Clément

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Duplicate Detection Using JavaScript

    Hi Suganthar ,

    Dynamics CRM support OOB duplicate detection rules you can go to settings - > Data Management -> Duplicate Detection Rules.

    You can select entity lead and add your condition . Its very easy to implement.

    Thanks

    Goutam

  • Suganthar_Satkunam Profile Picture
    Suganthar_Satkunam 210 on at
    RE: Duplicate Detection Using JavaScript

    Hi Clement. Thanks for the reply. I used the above WS call but I did not get any result to display. actual there is a duplicate record.

    Mainphone is telephone1

    mobile is mobilephone

    retrieveResult.open("GET", ODataPath +"/LeadSet?$select=FullName&$filter=(telephone1 eq "+mobilevalue+" or mobilephone eq "+mainphonevalue+")",false);

    I do not get any results at all. See my query below

    function CaptureMiRequirements_onSave(eventArgs) {
        var mobile = Xrm.Page.getAttribute("mobilephone");
        var email = Xrm.Page.getAttribute("emailaddress1");
        var mainPhone = Xrm.Page.getAttribute("telephone1");

        var isNull = mobile.getValue() == null && email.getValue() == null && mainPhone.getValue() == null;
        var isBlank = mainPhone.getValue() == "" && mobile.getValue() == "" && email.getValue() == "";
        var notificationMessage = "Error";

        if (isNull || isBlank) {
            Xrm.Page.ui.setFormNotification("To save this record, please enter either an Email address, Main Phone or Mobile number.", "ERROR", notificationMessage);
            eventArgs.preventDefault();
            eventArgs.returnValue = false;
        }
        else {
            Xrm.Page.ui.clearFormNotification(notificationMessage);
        }
       
       
        if (mainPhone.getValue() != null || mobile.getValue() != null)
        {
          
          var mainphonevalue= mainPhone.getValue();

          var mobilevalue=mobile.getValue();

           var context = Xrm.Page.context;

           var serverUrl = context.getClientUrl();

           var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";

           var retrieveResult = new XMLHttpRequest();

           alert(mainphonevalue);
           alert(mobilevalue);
           alert(context);
           alert(ODataPath);
      
           retrieveResult.open("GET", ODataPath +"/LeadSet?$select=FullName&$filter=(telephone1 eq "+mobilevalue+" or mobilephone eq "+mainphonevalue+")",false);
           retrieveResult.setRequestHeader("Accept", "application/json");
           alert("suga1");
           retrieveResult.setRequestHeader("Content-Type", "application/json; charset=utf-8?");
           alert("suga2");
           retrieveResult.send();
           alert("suga3")

          
           if (retrieveResult.readyState == 4 /* complete */)
           {
               if (retrieveResult.status == 200)
               {
        var retrieved = this.parent.JSON.parse(retrieveResult.responseText).d;
        var Result = retrieved.results;
         if (typeof Result !== "undefined")
         {
       Result.foreach(function(data){
        alert(data.FullName);
        // should display the lead full name
       });
       
         var count = Result.length;
         if (count>1)
         {
          alert("duplicate value not allowed");
          executionObj.getEventArgs().preventDefault();
         }
       }
            }
            }


           /*Xrm.Page.ui.setFormNotification(ODataPath, "ERROR", notificationMessage);
                           eventArgs.preventDefault();
                           eventArgs.returnValue = false;*/      
        
        }
    }

    in the above script, I get all the alert messages except lead's fullname and duplicate value not allowed. Can you please check my script and correct me where I'm failing here. As I'm newbie to CRm development, I'm still in the learning curve

  • Suggested answer
    Clem Profile Picture
    Clem 2,541 on at
    RE: Duplicate Detection Using JavaScript

    Hi,

    You approach is good. I didn't tell the whole JS to find out coding errors if there are but.

    Two points to complete your question:

    You call to WS should look like :

    retrieveResult.open("GET", ODataPath +"/LeadSet?$select=FullName&$filter=(telephone1 eq "+mobilevalue+" or mobilephone eq "+mainphonevalue+")",false);

    And the get the full name from there : 

    if (retrieveResult.readyState == 4 /* complete */)
    {
       if (retrieveResult.status == 200)
       {
    	   var retrieved = this.parent.JSON.parse(retrieveResult.responseText).d;
    	   var Result = retrieved.results;
    	   if (typeof Result !== "undefined")
    	   {
    			Result.foreach(function(data){
    				alert(data.FullName);
    				// should display the lead full name 
    			});
    	   
    		   var count = Result.length;
    		   if (count>1)
    		   {
    			   alert("duplicate value not allowed");
    			   executionObj.getEventArgs().preventDefault();
    		   }
    	   }
       }
    }


    a copy paste of that part might not be sufficent but you get the idea.
    In the variable Result you will get all leads and then from there, since in the query you select the fullname you can get it.

    Hope this help,

    Clément

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,269 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans