QUESTION:
My Lead scenario is set to auto-merge, but when I create a new Lead with a Campaign Member record that Campaign Member record is NOT being merged onto the existing matching Lead. What am I doing wrong?
ANSWER:
The Auto-merge action is done via asynchronous (@future) call which means the merge occurs after all insert triggers complete. If you create the campaign member record during insert – either via a before insert or after insert trigger - it will be on the incoming record prior to the merge and subsequently merge over to the existing record.
When inserting a Lead via the Salesforce User Interface you can directly populate a "field" called Campaign which then triggers the creation of a Campaign Member record when the Lead is saved. Salesforce Web to Lead functionality also allows passing a Campaign ID directly to the Lead record upon insertion. Both of these methods of Lead creation with Campaign members will work as desired when the records are auto-merged.
However, the Campaign "field" IS NOT available directly via the API (apex code). Therefore, custom code to directly create Campaign Member records done in a before or after update trigger WILL NOT get merged onto the master Lead as it is NOT present at the time of insert.
WORKAROUND:
Add a "Campaign ID" custom field to the Lead table. Populate the Campaign ID field when inserting the Lead, then have a trigger that checks if the field is populated. If it is populated, create the Campaign Member record after insert, but in the same Apex batch (i.e. synchronously....do not use an @future call). DupeBlocker's auto-merge would then fire (asynchronously) and the new Campaign will be merged onto the master (existing) Lead.
NOTE: This solution also applies for auto-converting Leads to Contacts.