Saturday, April 28, 2012

Copy related list from Lead to Account/Contact/Opportunity


There is a salesforce limitation that when a Lead is converted to Account, all the related objects records are lost. E.g. for a Lead, there is a related object named products in which a lead is interested. So for a lead, we can add multiple products in the Lead related list. But when we convert lead to Account, all the products related to Lead are gone!!

So for this, I have written a small code which explains how using a small trigger and few fields, we can retain the products by linking them to account, opportunities and contact. 

I have used a general term CustomObject__c(replace it with you real related object name).

Step 1)For each custom object related to Lead we need to introduce 3 fields.
  -Account__c
  -Contact__c
  -Opportunity__c

Step 2) Write a trigger on before update event on Lead viz. LeadBeforeUpdate
trigger LeadBeforeUpdate on Lead (before update) {
//This trigger will associate a Custom Object record with the new contact and account when Lead is converted
//The Custom Object is associated to an opportunity only if an opportunity record exist on the Lead.
   
    Set<Id> leadIds = new Set<Id>();
    Map<Id,Id> LeadIdContactId = new Map<Id,Id>();
    Map<Id,Id> LeadIdAccountId = new Map<Id,Id>();
    Map<Id,Id> LeadIdOpportunityId = new Map<Id,Id>();


    for (Integer i = 0; i < Trigger.new.size(); i++){
        if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false){
             leadIds.add(Trigger.new[i].id);
             LeadIdContactId.put(Trigger.new[i].id,Trigger.new[i].ConvertedContactId);
             LeadIdAccountId.put(Trigger.new[i].id,Trigger.new[i].ConvertedAccountId);
             LeadIdOpportunityId.put(Trigger.new[i].id,Trigger.new[i].ConvertedOpportunityId);


        }
    }
   
    //Create a list of CustomObject__c to be updated
    List<CustomObject__c> CustomObjectsToUpdate = new List<CustomObject__c>();
       
           
    List<CustomObject__c> customObjectEntries = [select Contact__c, Opportunity__c, Account__c, Lead__c from CustomObject__c where lead__c in :leadIds];       
   

    for (Lead lead : [select id,ConvertedContactId,ConvertedOpportunityId,ConvertedAccountId from Lead where id in: leadIds])  {
             for (CustomObject__c CustomObject : customObjectEntries) {
                if (CustomObject.Lead__c == lead.Id) {
                    CustomObject.contact__c = LeadIdContactId.get(lead.id);
                    CustomObject.opportunity__c = LeadIdOpportunityId.get(lead.id);
                    CustomObject.account__c = LeadIdAccountId.get(lead.id);
                    CustomObjectsToUpdate.add(CustomObject);
                 }
            }
     }

     if(CustomObjectsToUpdate.size()>0)
         update CustomObjectsToUpdate;
      
} //End of trigger


Note: This trigger will work for multiple records to be copied and is bulk efficient.