Match duplicates for record
Salesforce users must have an idea about the duplicate matching rules. This rule helps us to check if there are any duplicates available for the record being created or updated. The duplicate rules can be defined on a number of objects and they will be used to identify duplicates. What I wanted to discuss today is that how can we use these very duplicate rules in apex so that we can check for possible duplicated before trying to insert a record. This is what I’ll be talking about today, how to match duplicates for record.
APEX Code
Let’s get to the good part directly. The code for this part is really very simple, just use the below-mentioned classes.
public class createDuplicateAccount { public string accname { get; set;} private boolean allClear { get; set;} public createDuplicateAccount(){ allClear = true; } public void saveData(){ allClear = true; Account acc = new Account(name=accname); list accounts = new list(); accounts.add(acc); list ids = new list(); Datacloud.FindDuplicatesResult[] results = Datacloud.FindDuplicates.findDuplicates(accounts); for (Datacloud.FindDuplicatesResult dupeResult : results) { for (Datacloud.DuplicateResult dupeRes : dupeResult.getDuplicateResults()) { for (Datacloud.MatchResult matchRes : dupeRes.getMatchResults()) { for (Datacloud.MatchRecord matchRec : matchRes.getMatchRecords()) { allClear = false; ids.add((string)matchRec.getRecord().get('id')); } } } } if(!allClear){ apexpages.addMessage(new apexpages.Message(Apexpages.Severity.ERROR,'Duplicate Detected with these id(s): '+string.join(ids, ','))); }else{ try{ insert accounts; apexpages.addMessage(new ApexPages.message(Apexpages.Severity.CONFIRM,'Account Created Successfully')); }catch(exception e){ apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,e.getMessage())); } } } }
In the above code, we have user a FindDuplicates class with namespace DataCloud and got all the duplicate rules for the mentioned list of sObjects. After that, we have looped over all the duplicate rules to get the results for each rule individually. For each duplicate rule we have different matching rules and with each rule, we got individual records. This is how we got if any record in the list will give a positive on any matching rule.
To test this functionality let us make a VF page.
<apex:page controller="createDuplicateAccount"> <apex:form > <apex:pageMessages id="errors"/> <apex:inputText value="{!accName}"/> <apex:commandButton value="Save" action="{!saveData}" rerender="errors"/> </apex:form> </apex:page>
Output
Support
That’s all about duplicate matching in APEX, for any further queries feel free to contact us at:
https://wedgecommerce.com/contact-us/
Or let us know your views about this blog in the comments section below.