0

Scenario: I have a Lead record and it's single child record. On this child record of Lead I have a look up of Contact and Account also.

Whenever a Lead is converted to Account and Contact, I want to map that Account and Contact on the child record of Lead.

I'm writing a trigger on Contact in after Insert Context as below. But I'm not able to get the Lead Record using the ContactId in this Trigger. I have also tried doing it using flow, but it gives the same issue.

trigger ContactTrigger on Contact (after insert) {
    if(trigger.isAfter && trigger.isInsert){
        set<string> setContactId = new set<string>();
        List<Lead> lstLead = new List<Lead>();
        List<Child_Object__c> lstCh = new List<Child_Object__c>();
        List<Child_Object__c> lstChToUpdate = new List<Child_Object__c>();
        
        for(Contact objCon:Trigger.new){
            if(objCon.Converted_from_Lead__c == true){
                setContactId.add(objCon.Id);
            }
        }
        system.debug('setContactId--'+setContactId); // I get the contact Id here
        
        Map<string,Lead> mapIdAndLead = new Map<string,Lead>();
        
        if(setContactId != null && setContactId.size() > 0){
            lstLead = [select id,Name,MobilePhone,Status,IsConverted,ConvertedAccountId, ConvertedContactId,ConvertedContact.Name 
                       from Lead 
                       where ConvertedContactId =: setContactId]; // I don't get the lead record here so nothing proceeds further
        }
        
        if(lstLead != null && lstLead.size() > 0){
            for(Lead objLd:lstLead){
                mapIdAndLead.put(objLd.Id,objLd);
            }
            
            lstCh = [select Id,Name,Lead__c,Contact__c,Account__c from Child_Object__c where Lead__c =: mapIdAndLead.keySet()];
            
            for(Child_Object__c objCh:lstCh){
                if(mapIdAndLead.containsKey(objCh.Lead__c)){
                    Lead objLead = mapIdAndLead.get(objCh.Lead__c);
                    objCh.Contact__c = objLead.ConvertedContactId;
                    objCh.Account__c = objLead.ConvertedAccountId;
                    lstChToUpdate.add(objCh);
                }
            }

            if(lstChToUpdate != null && lstChToUpdate.size() > 0){
                update lstChToUpdate;
            }
        }
    }
}
1
  • PS. lstChToUpdate is never null, as a query cannot be a null object, and lstChToUpdate.size() > 0 is unnecessary, as the DML operations do this for you anyways (to avoid wasting governor limits).
    – sfdcfox
    Commented Apr 28, 2023 at 20:04

1 Answer 1

0

You need to put the trigger on the Lead object. The lead trigger fires after the Account, Contact, and Opportunity records have had their triggers executed. See this answer. As a bonus, you get this action for free, so you don't need to do any queries at all.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .