Trigger to update losing lead information to winning Lead in merge in Salesforce

Trigger to update losing lead information to winning Lead in merge in Salesforce

Apex Class:

public class LeadMerge {
    @future
    public static void updateLeadAfterMerge(Map<Id, String> mapLeadIdLeadSource) {
        List<Lead> listLead = new List<Lead>();
        for(Id leadId : mapLeadIdLeadSource.keySet()) {
            listLead.add(new Lead(Id = leadId, Lead_Source_Detail__c = mapLeadIdLeadSource.get(leadId)));
        }
        update listLead;
    }
}

Trigger:

trigger LeadMergeTrigger on Lead (after delete) {
    Map<Id, String> mapLeadIdLeadSource = new Map<Id, String>();
    for(Lead l : trigger.old) {
        if(String.isNotBlank(l.MasterRecordId)) { 
            mapLeadIdLeadSource.put(l.MasterRecordId, l.LeadSource);  
        }         
    }
    if(mapLeadIdLeadSource.size() > 0) {
        LeadMerge.updateLeadAfterMerge(mapLeadIdLeadSource);
    }    
}

Note:

Lead_Source_Detail__c is a custom field created in Lead to capture deleted lead’s Lead Source.

Leave a Reply