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.

Cheers!!!

3 comments:

  1. HI, thanks for your immediate response. Here instead of updating the loser lead source information in custom field it is updating the Winner`s lead source information in Lead source detail custom field.

    Can you please recheck again. Thank you a ton.

    Thanks,
    Ezhil.

    ReplyDelete
    Replies
    1. Please double check from your end. It is working fine.

      Delete
  2. Hi Magulan, Did u check the code once again. Because still its updating winner`s lead source rather than updating Loser`s lead source record.

    Your response is highly appreciated.

    Thanks,

    ReplyDelete