function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MaheemSamMaheemSam 

Update inside for loop

Hi, 

  In below helper class i have commented there are two condition update for contact and lead Please suggest me how to make this out of for loop and code bulkified.  Please suggest
public class CtapAssessmentTriggerUtils { 
  
    public static void processInsert(List<CTAP_Assessment__c> newLst) {
        List<Contact> cntlst = new List<Contact>();
        List<Lead>    ledlst = new List<Lead>();
        Set<String> emailSet = new Set<String>();
        Set<String> partnerSet = new Set<String>();
        Lead l = new lead();
        
        Map<String, Id> mapEmailToConId = new Map<String, Id>();
        Map<String, Id> mapEmailToLeadId = new Map<String, Id>();
        List<Lead> newLeadLst = new List<Lead>();
        Map<String, CTAP_Assessment__c> newLeadforCtapMap = new Map<String, CTAP_Assessment__c> ();
        Map<Id,Id> PartnerActMap = new Map<Id,Id>();
         
        // collect emails in a set
        for(CTAP_Assessment__c ctap : newLst) {
            CountryCodeMap__c codeMap = CountryCodeMap__c.getInstance(ctap.Country_Code__c);                   
            system.debug('__kkk__' +codeMap);
            if(codeMap != null) {
                ctap.End_Customer_Country__c = codeMap.Country_Name__c;
            }
            emailSet.add(ctap.Contact_Email__c);
            partnerSet.add(ctap.Partner_Account__c);
            system.debug('ctap.Contact_Email__c ' + ctap.Contact_Email__c);
        }
        // removing nulls
        emailSet.remove(null);
        
        system.debug('emailSet '  + emailSet);
        
        if(!emailSet.isEmpty()) {
            for(Contact objCon : [select id,email from contact where email IN :emailSet]){
                mapEmailToConId.put(objCon.Email, objCon.Id);
                objCon.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Contact Lead Source added by Sudhir
                cntlst.add(objCon);
            }
            
            for(Lead objLead: [select id,email from Lead where email IN :emailSet]){
                mapEmailToLeadId.put(objLead.Email, objLead.Id);
                objLead.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Lead Source added by Sudhir
                ledlst.add(objLead);
            }
        }        
                
         for(Account ObjPartnerAct : [select id,owner.name,ownerid from account where id in :partnerSet]){
            PartnerActMap.put(ObjPartnerAct.id,ObjPartnerAct.ownerid);
         }
         
        // asssign based on map key match with email
        for(CTAP_Assessment__c ctap : newLst){
            if( mapEmailToConId.get(ctap.Contact_Email__c) != null){
              ctap.Contact__c = mapEmailToConId.get(ctap.Contact_Email__c);
              ctap.Lead__c = null;
                if (!cntlst.isEmpty()){  // Conditional update contact
                   update cntlst;
                  }
             }else if ( mapEmailToLeadId.get(ctap.Contact_Email__c) != null) {
              ctap.Lead__c = mapEmailToLeadId.get(ctap.Contact_Email__c);
              ctap.Contact__c = null;
                   if (!ledlst.isEmpty()){ //Conditional update lead
                   update ledlst;
                  }
              }
              else {         
                  // Create a new lead         
                  l.Company = ctap.End_Customer_Name__c;
                  l.FirstName = ctap.Contact_First_Name__c; 
                  l.LastName = ctap.Contact_Last_Name__c; 
                  l.Email = ctap.Contact_Email__c;
                  l.Phone = ctap.Phone__c;
                  l.Title = ctap.Title__c;
                  l.Industry = ctap.Industry__c;
                  l.Lead_Source_Temp__c = 'CTAP Assessement';
                  l.LeadSource = 'CTAP Assessement';
                  l.street = ctap.Address__c;
                  l.Country = ctap.End_Customer_Country__c;
                  l.State = ctap.state__c;
                  l.Postalcode = ctap.postalcode__c;
                  l.Employee_Size__c = ctap.Employee_Size__c;  

                  if(ctap.Country_Code__c == 'US') {// verify for the Assignment rule test for US 
                      l.Run_Assignment_Rule__c = true;
                  } else if(ctap.Partner_Account__c !=  null && ( ctap.Country_Code__c != 'US') ){ //Here it checks only for country USA
                    l.Ownerid = PartnerActMap.get(ctap.Partner_Account__c);  
                  }  
                                              
                 if(ctap.Contact_Email__c <> null && 
                    ctap.End_Customer_Country__c <> null &&
                    ctap.End_Customer_Name__c <> null &&
                    ctap.Contact_First_Name__c <> null ) {                                                    
                   newLeadLst.add(l);
                  }
                  
                 newLeadforCtapMap.put(ctap.Contact_Email__c, ctap);
             
          } 
        }
        
           if ( !newLeadLst.isEmpty() ){
                insert newLeadLst;
                    
                 for(Lead lead : newLeadLst){
                    CTAP_Assessment__c ctap = newLeadforCtapMap.get(lead.Email);
                    ctap.Lead__c = lead.id; //Assign new lead to ctap lead
                 }
            }
    }
     
    public static void processUpdate(Map<id,CTAP_Assessment__c> newMap, Map<id,CTAP_Assessment__c> oldMap) {
        List<CTAP_Assessment__c> changedLst = new List<CTAP_Assessment__c>();
        for(CTAP_Assessment__c ctap : newMap.values()){
            CTAP_Assessment__c oldCtap = oldMap.get(ctap.id);
              if(ctap.Contact_Email__c != null){
                changedLst.add(ctap);
            }
        
            if(!changedLst.isEmpty())
                processInsert(changedLst);
        }
    }
    
  
    
  
}

Thanks
Sudhir
EldonEldon
Hi,

Use a flag variable to set a flag inside for loop and update outside the for loop based on the value of flag variables,
 
public class CtapAssessmentTriggerUtils { 
  
    public static void processInsert(List<CTAP_Assessment__c> newLst) {
        List<Contact> cntlst = new List<Contact>();
        List<Lead>    ledlst = new List<Lead>();
        Set<String> emailSet = new Set<String>();
        Set<String> partnerSet = new Set<String>();
        Lead l = new lead();
        
        Map<String, Id> mapEmailToConId = new Map<String, Id>();
        Map<String, Id> mapEmailToLeadId = new Map<String, Id>();
        List<Lead> newLeadLst = new List<Lead>();
        Map<String, CTAP_Assessment__c> newLeadforCtapMap = new Map<String, CTAP_Assessment__c> ();
        Map<Id,Id> PartnerActMap = new Map<Id,Id>();
         
        // collect emails in a set
        for(CTAP_Assessment__c ctap : newLst) {
            CountryCodeMap__c codeMap = CountryCodeMap__c.getInstance(ctap.Country_Code__c);                   
            system.debug('__kkk__' +codeMap);
            if(codeMap != null) {
                ctap.End_Customer_Country__c = codeMap.Country_Name__c;
            }
            emailSet.add(ctap.Contact_Email__c);
            partnerSet.add(ctap.Partner_Account__c);
            system.debug('ctap.Contact_Email__c ' + ctap.Contact_Email__c);
        }
        // removing nulls
        emailSet.remove(null);
		
        boolean flagcnt = false;
		boolean flagled = false;
		
        system.debug('emailSet '  + emailSet);
        
        if(!emailSet.isEmpty()) {
            for(Contact objCon : [select id,email from contact where email IN :emailSet]){
                mapEmailToConId.put(objCon.Email, objCon.Id);
                objCon.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Contact Lead Source added by Sudhir
                cntlst.add(objCon);
            }
            
            for(Lead objLead: [select id,email from Lead where email IN :emailSet]){
                mapEmailToLeadId.put(objLead.Email, objLead.Id);
                objLead.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Lead Source added by Sudhir
                ledlst.add(objLead);
            }
        }        
                
         for(Account ObjPartnerAct : [select id,owner.name,ownerid from account where id in :partnerSet]){
            PartnerActMap.put(ObjPartnerAct.id,ObjPartnerAct.ownerid);
         }
         
        // asssign based on map key match with email
        for(CTAP_Assessment__c ctap : newLst){
            if( mapEmailToConId.get(ctap.Contact_Email__c) != null){
              ctap.Contact__c = mapEmailToConId.get(ctap.Contact_Email__c);
              ctap.Lead__c = null;
                <b>if (!cntlst.isEmpty()){  // Conditional update contact
                   //update cntlst;
				   flagcnt = true;
                  }</b>
             }else if ( mapEmailToLeadId.get(ctap.Contact_Email__c) != null) {
              ctap.Lead__c = mapEmailToLeadId.get(ctap.Contact_Email__c);
              ctap.Contact__c = null;
                   <b>if (!ledlst.isEmpty()){ //Conditional update lead
                   //update ledlst;
				   flagled = true; 
                  }</b>
              }
              else {         
                  // Create a new lead         
                  l.Company = ctap.End_Customer_Name__c;
                  l.FirstName = ctap.Contact_First_Name__c; 
                  l.LastName = ctap.Contact_Last_Name__c; 
                  l.Email = ctap.Contact_Email__c;
                  l.Phone = ctap.Phone__c;
                  l.Title = ctap.Title__c;
                  l.Industry = ctap.Industry__c;
                  l.Lead_Source_Temp__c = 'CTAP Assessement';
                  l.LeadSource = 'CTAP Assessement';
                  l.street = ctap.Address__c;
                  l.Country = ctap.End_Customer_Country__c;
                  l.State = ctap.state__c;
                  l.Postalcode = ctap.postalcode__c;
                  l.Employee_Size__c = ctap.Employee_Size__c;  

                  if(ctap.Country_Code__c == 'US') {// verify for the Assignment rule test for US 
                      l.Run_Assignment_Rule__c = true;
                  } else if(ctap.Partner_Account__c !=  null && ( ctap.Country_Code__c != 'US') ){ //Here it checks only for country USA
                    l.Ownerid = PartnerActMap.get(ctap.Partner_Account__c);  
                  }  
                                              
                 if(ctap.Contact_Email__c <> null && 
                    ctap.End_Customer_Country__c <> null &&
                    ctap.End_Customer_Name__c <> null &&
                    ctap.Contact_First_Name__c <> null ) {                                                    
                   newLeadLst.add(l);
                  }
                  
                 newLeadforCtapMap.put(ctap.Contact_Email__c, ctap);
             
          } 
        }
		
		//update lists based on flag 
        if(flagcnt == true){
			update cntlst;
		}
		if(flagled == true){
			update ledlst;
		}
		
           if ( !newLeadLst.isEmpty() ){
                insert newLeadLst;
                    
                 for(Lead lead : newLeadLst){
                    CTAP_Assessment__c ctap = newLeadforCtapMap.get(lead.Email);
                    ctap.Lead__c = lead.id; //Assign new lead to ctap lead
                 }
            }
    }
     
    public static void processUpdate(Map<id,CTAP_Assessment__c> newMap, Map<id,CTAP_Assessment__c> oldMap) {
        List<CTAP_Assessment__c> changedLst = new List<CTAP_Assessment__c>();
        for(CTAP_Assessment__c ctap : newMap.values()){
            CTAP_Assessment__c oldCtap = oldMap.get(ctap.id);
              if(ctap.Contact_Email__c != null){
                changedLst.add(ctap);
            }
        
            if(!changedLst.isEmpty())
                processInsert(changedLst);
        }
    }
    
  
    
  
}

Regards
MaheemSamMaheemSam
Thanks for you reply I tried to update using a MAP Please see below code if this is best practice this is also working not sure if this is bulified Please suggest.
public class CtapAssessmentTriggerUtils { 
  
    public static void processInsert(List<CTAP_Assessment__c> newLst) {
        Map<Id, Contact> CntUpdate = new Map<Id, Contact>(); 
        Map<Id, Lead> LedUpdate = new Map<Id, Lead>(); 
        List<Contact> cntlst = new List<Contact>();
        List<Lead>    ledlst = new List<Lead>();
        
        Set<String> emailSet = new Set<String>();
        Set<String> partnerSet = new Set<String>();
        Lead l = new lead();
        
        Map<String, Id> mapEmailToConId = new Map<String, Id>();
        Map<String, Id> mapEmailToLeadId = new Map<String, Id>();
        List<Lead> newLeadLst = new List<Lead>();
        Map<String, CTAP_Assessment__c> newLeadforCtapMap = new Map<String, CTAP_Assessment__c> ();
        Map<Id,Id> PartnerActMap = new Map<Id,Id>();
         
        // collect emails in a set
        for(CTAP_Assessment__c ctap : newLst) {
            CountryCodeMap__c codeMap = CountryCodeMap__c.getInstance(ctap.Country_Code__c);                   
            system.debug('__kkk__' +codeMap);
            if(codeMap != null) {
                ctap.End_Customer_Country__c = codeMap.Country_Name__c;
            }
            emailSet.add(ctap.Contact_Email__c);
            partnerSet.add(ctap.Partner_Account__c);
            system.debug('ctap.Contact_Email__c ' + ctap.Contact_Email__c);
        }
        // removing nulls
        emailSet.remove(null);
        
        system.debug('emailSet '  + emailSet);
        
        if(!emailSet.isEmpty()) {
            for(Contact objCon : [select id,email from contact where email IN :emailSet]){
                mapEmailToConId.put(objCon.Email, objCon.Id);
                objCon.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Contact Lead Source added by Sudhir
                cntlst.add(objCon);
                //CntUpdate.put(objCon.id,objCon);
            }
            
            for(Lead objLead: [select id,email from Lead where email IN :emailSet]){
                mapEmailToLeadId.put(objLead.Email, objLead.Id);
                objLead.Lead_Source_Temp__c = 'CTAP Assessement'; //Update Lead Source added by Sudhir
                ledlst.add(objLead);
                //LedUpdate.put(objLead.id,objLead);
            }
        }        
                
         for(Account ObjPartnerAct : [select id,owner.name,ownerid from account where id in :partnerSet]){
            PartnerActMap.put(ObjPartnerAct.id,ObjPartnerAct.ownerid);
         }
         
        // asssign based on map key match with email
        for(CTAP_Assessment__c ctap : newLst){
            if( mapEmailToConId.get(ctap.Contact_Email__c) != null){
              ctap.Contact__c = mapEmailToConId.get(ctap.Contact_Email__c);
              ctap.Lead__c = null;   
              CntUpdate.putall(cntlst);  //Using Map to update  Sudhir  
             }else if ( mapEmailToLeadId.get(ctap.Contact_Email__c) != null) {
              ctap.Lead__c = mapEmailToLeadId.get(ctap.Contact_Email__c);
              ctap.Contact__c = null;  
              LedUpdate.putall(ledlst);   //Using Map to update Sudhir          
              }
              else {         
                  // Create a new lead         
                  l.Company = ctap.End_Customer_Name__c;
                  l.FirstName = ctap.Contact_First_Name__c; 
                  l.LastName = ctap.Contact_Last_Name__c; 
                  l.Email = ctap.Contact_Email__c;
                  l.Phone = ctap.Phone__c;
                  l.Title = ctap.Title__c;
                  l.Industry = ctap.Industry__c;
                  l.Lead_Source_Temp__c = 'CTAP Assessement';
                  l.LeadSource = 'CTAP Assessement';
                  l.street = ctap.Address__c;
                  l.Country = ctap.End_Customer_Country__c;
                  l.State = ctap.state__c;
                  l.Postalcode = ctap.postalcode__c;
                  l.Employee_Size__c = ctap.Employee_Size__c;  

                  if(ctap.Country_Code__c == 'US') {// verify for the Assignment rule test for US 
                      l.Run_Assignment_Rule__c = true;
                  } else if(ctap.Partner_Account__c !=  null && ( ctap.Country_Code__c != 'US') ){ //Here it checks only for country USA
                    l.Ownerid = PartnerActMap.get(ctap.Partner_Account__c);  
                  }  
                                              
                 if(ctap.Contact_Email__c <> null && 
                    ctap.End_Customer_Country__c <> null &&
                    ctap.End_Customer_Name__c <> null &&
                    ctap.Contact_First_Name__c <> null ) {                                                    
                   newLeadLst.add(l);
                  }
                  
                 newLeadforCtapMap.put(ctap.Contact_Email__c, ctap);
             
          } 
        }
        
            if(CntUpdate.size()>0){
              update CntUpdate.values();        
            }
            
            
            if(LedUpdate.size()>0){
              update LedUpdate.values();      
            }
           
           
        
           if ( !newLeadLst.isEmpty() ){
                insert newLeadLst;
                    
                 for(Lead lead : newLeadLst){
                    CTAP_Assessment__c ctap = newLeadforCtapMap.get(lead.Email);
                    ctap.Lead__c = lead.id; //Assign new lead to ctap lead
                 }
            }
    }
     
    public static void processUpdate(Map<id,CTAP_Assessment__c> newMap, Map<id,CTAP_Assessment__c> oldMap) {
        List<CTAP_Assessment__c> changedLst = new List<CTAP_Assessment__c>();
        for(CTAP_Assessment__c ctap : newMap.values()){
            CTAP_Assessment__c oldCtap = oldMap.get(ctap.id);
              if(ctap.Contact_Email__c != null){
                changedLst.add(ctap);
            }
        
            if(!changedLst.isEmpty())
                processInsert(changedLst);
        }
    }
    
  
    
  
}

Thanks
Sudhir