Bypass account or contact duplicate rules in during lead conversion
Use-Case
We have several integrations from which the leads are coming to Salesforce. We have different processes to handle those leads, to avoid duplicates we have duplicate rules. However, there is one-system, from which we don't want the duplicate rules to run, because of a business requirement. The business process is handled in the LeadTrigger.
Solutions
There are two ways to achieve this
- Through applying filters on the duplicate rules, and skipping them for specific users or conditions
- Through Apex - simplified solution here was to update only the specific lead process where we needed to skip duplicate rules, hence went for the Apex code here.
Problem - above solution works well if you have a simplified or singular lead process, we have multiple lead sources coming from integrations, web-to-lead, and UI, therefore, above solution would be applied to all lead processes. Hence, cant use the above solution.
//creating lead Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons', Email='fry@mail.com'); insert myLead; // creating lead instance Database.LeadConvert lc = new database.LeadConvert(); lc.setLeadId(myLead.id); // **optional LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1]; lc.setConvertedStatus(convertStatus.MasterLabel); // skipping duplicate rules Database.DMLOptions dml = new Database.DMLOptions(); dml.DuplicateRuleHeader.AllowSave = true; // converting lead Database.LeadConvertResult lcr = Database.convertLead(lc, dml); if (lcr.isSuccess()) { System.debug('Duplicate contact has been inserted in Salesforce!'); } else system.debug('>>> Error Inserting Duplicate: '+ lcr.getErrors());
- The AllowSave only works if the duplicate rule is an Alert rule, not a Block rule.
- As per the SF documentation, "The Database.convertLead() method can take one LeadConvert object or a list of LeadConvert objects.", however, this method can take 2nd parameter of type DMLOptions. A hidden gem!
- The above code assumes that you have a duplicate rule active on either Account or Contact or even both.
No comments:
Post a Comment