Thursday, 7 June 2018

Salesforce - Copy Lead related lists to Opportunity Related list after lead conversion

trigger CopyLeadRelatedListsToOpportunity 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<Time_Service__c> CustomObjectsToUpdate = new List<Time_Service__c>();
     
         
    List<Time_Service__c> customObjectEntries = [select case__c, Opportunity__c, Lead__c from Time_Service__c where lead__c in :leadIds];     
 

    for (Lead lead : [select id,ConvertedContactId,ConvertedOpportunityId,ConvertedAccountId from Lead where id in: leadIds])  {
             for (Time_Service__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

No comments:

Post a Comment