+ Start a Discussion
Sanjeev R 1Sanjeev R 1 

Best practice to bulkify the trigger

I have before update trigger on Opportunity.
Basically I need to bulkify the trigger..

When uploading data via data loader I will have list of opportunities

Oppounity[] getOpps = Trigger.new;

Now need to find the email address of Contact (Lookup) with each of these incoming opportunities..

If I will put a SOQL qurey in for loop for each opportunity.. it will hit the governer limits if I have says +100 records...

How can I have a workaround for this in apex ... so that I don't need to make a SQOL query inside the for loop in this case

thanks in advance


RamuRamu (Salesforce Developers) 
To do this, you would need to make use of maps. Make a map of id and string to store contact id's and their email id's which serves as a local datasource. Then you need to loop through the trigger.new collection and check if the contact id associated to a particular opportunity exist in the map collection, if yes, get the corresponding email id.

Please review the below articles to get fair idea on maps



You need to understand the following things

1. Execution order of Apex.
2. Make a good confidenct in Map,List and Set Collections.
3. Learn how to avoid recursion

That's It !

If you find this answer useful please mark it as solution.

Thanks !
Balaji BondarBalaji Bondar
Use collection data types to bulkfy the triggers:
Map<Id, String> OppIdContactMap = new Map<Id, String>();

for(Opportunity opportunity : [Select Id, Contact__r.Email from Opportunity where Id IN: Trigger.New]){
	OppIdContactMap.put(opportunity.Id , opportunity.Contact__r.Email);

for(Opportunity opportunity : Trigger.New){
String contactEmailAddress = OppIdContactMap.get(opportunity.Id);

Important :
If this is what you were looking for then please mark it as a "SOLUTION" or You can Click on the "Like" Button if this was beneficial for you.
Sanjeev R 1Sanjeev R 1

Thanks Balaji Bondar
it make things easier to co-relate and  learn when you get the related help to the sutiation you are in at the moment..
the code snippet above is really helpful. :) 

Thanks Ramu,
these links are really helpful

Thanks  Shiv@SFDC
yes I will go thr. Map,List and Set Collections as these are the bulding blocks to avoid recursion 

thanks Anoop