Salesforce.com Code Optimization

Trey AroseSalesforce, Technical TipsLeave a Comment

Rule #1:

When developing custom Apex code in Salesforce.com, it is not enough to simply create a working trigger to fit your specific scenario, you must also take into consideration bulk data loading.

If your trigger cannot handle loading multiple records, you will hit the error [message_box title=”Error:” color=”red”]System.LimitException: Too many SOQL queries: 101[/message_box] This error is typically caused by having a SOQL query within a for loop.  To remedy this,  you must add  your SOQL query before your for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Set<Id> projIds = new Set <Id>();
//Add Project and Program Id into two sets.
for(Account aId : Trigger.New){
progIds.add(aId.Program__c);
}
//Query the Program and Project object for the desired values
Map<Id, Project__c>; i = new Map<Id,Project__c>;([SELECT Id, Project_Manager__c from Project__c where Id IN :projIds]);
Map<Id,Program__c>; p = new Map<Id,Program__c>;([SELECT Id, Program_Manager__c  from Program__c where Id IN :progIds]);
 
//Loop through each Account adding in the values
for(Account a: Trigger.New){
if(a.Project__c !=null){
 
a.Project_Manager__c = i.get(pcr.Project__c).Project_Manager__c;
a.Program_Manager__c = p.get(pcr.Program__c).Program_Manager__c;
 
}
}

This trigger can handle not only single record updating, but also bulk data jobs, without hitting the SOQL limit.

Leave a Reply

Your email address will not be published. Required fields are marked *