Insert related record when DUPLICATES_DETECTED error is thrown from Salesforce Matching Rule

apexdmlduplicate-managementexception

I have a requirement to insert CampaignMembers whenever a duplicate Lead is identified.

The duplicate check for all Leads of all Lead sources is handled via Standard Duplicate rule. This rule needs to be active for all Lead Sources. Now, a new Lead Source also requires a further action ie , adding a Campaign Member whenever there is a Duplicate Lead found.

For Ex:

Assume there is a Lead , L1, called John Doe and has a email '[email protected]' that already exists.

Now, when a user tries to add a new Lead 'John Doe' (in which ever way UI, Apex, API etc), the expected reult is that the duplicate rule should prevent this new Lead from being inserted and at the same time, create a Campaign Member using the LeadId of the original Lead (L1) and a particular Campaign Id.

The issue is that as soon as the DUPLICATES_DETECTED error is thrown, the transaction rolls back and all further DML is lost.

Also, since the user tries to insert it from UI, there is no way to add the initial Lead insert DML in a try catch block.

I have tried to include the CampaignMember DML in a future method, in a queueable class and both did not work.

Can you please tell me how I can insert the CampaignMember records even though the transaction rolls back?

Best Answer

You can use a Before Insert Trigger or Before Save Flow to trigger a Platform Event that is set to Publish Immediately, which will allow the creation of the Campaign Member to occur asynchronously in a Platform Event Trigger, despite the transaction ultimately failing. Any other means, as you've discovered, don't work, because even asynchronous code (Batchable, Queueable, Schedulable, future methods, Publish-on-Commit Platform Events, emails) are all rolled back on a transaction failure.