+ Start a Discussion
@anilbathula@@anilbathula@ 

soql limit error.

Hi guys,

 

I have written a trigger to insert a custom objects record which are linked with lead to attch contact and opportunity on lead conversion.

But it is hitting soql limit on bulk Conversion.

Due to soql in for loop.

Please help from this problem.

 

 

trigger Commentsonconvert on Lead (after update,after insert) {
 Lead ld;
  List<Comments__c> Com = new List<Comments__c>();
 
  for(Lead l: Trigger.New){
      ld=l;
  
  if(ld.isConverted == true){  
   list <Comments__c>cs=[Select id,Contact__c, Opportunity__c from Comments__c where Lead__c=:ld.id];               
      for (Comments__c comTemp :cs ){
          comTemp.Opportunity__c = ld.ConvertedOpportunityId;
          if(ld.lastname!=null){
              comTemp.Contact__c=ld.ConvertedContactId;
          }
          Com.add(comTemp);
      }
  }
}
  if(Com !=null) update Com;
  
}

 

Thanks

Anil.B

SLockardSLockard

I wrote this real quick, so there might be a stupid typo or something, but you're trigger should be like this:

trigger Commentsonconvert on Lead (after update,after insert) 
{
	List<String> leadIDs = new List<String>();;
	List<Comments__c> Com = new List<Comments__c>();
	List<Lead> leads = new List<Leads>();
	 
	for(Lead l: Trigger.New)
	{
		if (l.isConverted == true)
		{
			leadIDs.add(l.Id);
			leads.add(l);
		}
	}
	list <Comments__c> cs = [Select id,Contact__c, Opportunity__c, Lead__c from Comments__c where Lead__c IN :leadIDs];               
	for (Comments__c comTemp :cs )
	{
		for (Lead ld : leads)
		{
			if (conTemp.Lead__c == ld.Id)
			{
				comTemp.Opportunity__c = ld.ConvertedOpportunityId;
				if(ld.lastname != null)
				{
					comTemp.Contact__c = ld.ConvertedContactId;
				}
				Com.add(comTemp);
			}
		}
	  }
	}
	if(Com !=null)
	{
	  update Com;  
	}
}

 

SamuelDeRyckeSamuelDeRycke

have a look at some of the apex best practises : http://wiki.developerforce.com/page/Apex_Code_Best_Practices