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:
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:
Cheers!
0 comments:
Post a Comment