Share this blog!

Salesforce  declarative model encompasses duplicate rules, which plays a major role in avoiding duplicate records. However, achieving the same goal in programmatical model can be a bit tricky. Of course we can always go for the brute force method where we can manually compare each field but if we can define duplicate rules and use them in the code, it would be more efficient and maintainable.

In this article, we will be looking at how to access and use duplicate rules in Apex.

For this article, I will be using a sample custom object and apply a duplicate rule as follows:



Even though the duplicate rule is configured to "Allow" creation and update, when using Apex code to create a duplicate record, the following error would be thrown.




In order to handle this kind of errors during Apex code execution (because we wouldn't want these errors shown to customers, do we?), the following approaches can be used.

1. Insert and capture the error:


The duplicate rule can be captured by the errors thrown at insertion as follows:


Class__c classToCreate = new Class__c(Name='Science', Grade__c=8);

Database.SaveResult saveResult = Database.insert(classToCreate, 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();
    
            System.debug(duplicateResult.getErrorMessage());
            
            Datacloud.MatchResult matchResult = duplicateResult.getMatchResults()[0];
            Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
            
            for (Datacloud.MatchRecord matchRecord : matchRecords) {
                System.debug('MatchRecord: ' + matchRecord.getRecord());
            }   
        }
 }
}



2. Find if duplicates exist before insertion:


If you want to check for duplicates before trying to insert, that too can be done using the FindDuplicates class in Datacloud namespace.



Class__c classToCreate = new Class__c(Name='Science', Grade__c=8);
List<Class__c> duplicates = findDuplicateRecords(classToCreate);
if(duplicates.size() == 0){
    //no duplicates
    insert classToCreate;
} else{
    //desired update
}


public static List<SObject> findDuplicateRecords(Class__c classToCreate){
 List<Class__c> classList = new List<Class__c>();
    classList.add(classToCreate);
        
    List<Datacloud.FindDuplicatesResult > findDuplicatesResult = Datacloud.FindDuplicates.findDuplicates(classList);
        
    Datacloud.DuplicateResult duplicateResult = findDuplicatesResult.get(0).getDuplicateResults().get(0);
    Datacloud.MatchResult matchResult = duplicateResult.getMatchResults()[0];
    List<Datacloud.MatchRecord> matchRecords = matchResult.getMatchRecords();
    
    List<SObject> duplicates = new List<SObject>();
    for(Datacloud.MatchRecord matchRecord : matchRecords){
        SObject duplicate = matchRecord.getRecord();
        System.debug('Match Record: ' + duplicate);
        duplicates.add(duplicate);
    }
    return duplicates;
}


Resources:

  1. Datacloud Namespace
  2. FindDuplicates class

Cheers!



Next PostNewer Posts Previous PostOlder Posts Home