function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Procurement ExecutiveProcurement Executive 

Update contacts if it caught as duplicate via trigger ?

I have a requirement while creating contact if it already exists then it will update the existing ones.
For example we have 2 contacts which are duplicate and while creating new contact it shows us that already two contacts are there with same data. In that case newer one updates it info into the existing ones. I am trying it with trigger on contact.

trigger ContactDuplicateTrigger on Contact (before insert) {
   //private final Contact contact;
    
    // Initialize a list to hold any duplicate records
    private List<sObject> duplicateRecords;
    
    // Define variable that’s true if there are duplicate records
    public boolean hasDuplicateResult{get;set;}
    
    Profile userProfile = [SELECT Id FROM Profile WHERE Name='Sales User'];
    if(userProfile.Id = UserInfo.getProfileId())
    return;

    Contact cont = new Contact( FirstName= 'Robin', LastName='Singh',Email='pintub.sfdc@gmail.com' );
    Database.SaveResult saveResult = Database.insert(cont, false);
    if (!saveResult.isSuccess()) {
    for (Database.Error error : saveResult.getErrors()) {
     if (error instanceof Database.DuplicateError) {
         Database.DuplicateError duplicateError = (Database.DuplicateError)error;
         Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();

         ApexPages.Message errorMessage = new ApexPages.Message(
                            ApexPages.Severity.ERROR, 'Duplicate Error: ' + 
                            duplicateResult.getErrorMessage());
         ApexPages.addMessage(errorMessage);

         this.duplicateRecords = new List<sObject>();

         Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();

         Datacloud.MatchResult matchResult = matchResults[0];
         Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
         this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
     }
}
}
ANUTEJANUTEJ (Salesforce Developers) 
Hi there,

I think you could do something like this:

>> get all the records with the parameter you are trying to check on the duplicates and check if there are any duplicates in case if there are any duplicates create a map with id as the key and the list of records with old and new values as the value of the map.

>> Pass the map to the function and in this function, you can update the old records with the new values.

I hope this helps and in case if this comes handy can you please choose this as best answer so that it can be used by others in the future.

Regards,
Anutej