http://wiki.developerforce.com/page/Best_Practice:_Bulkify_Your_Code
- Create a SET before entering trigger.new that will hold the ID of all SObjects being updated or looped through
- Pull a list of the IDs of the SObjects that need to be updated when looping through trigger.new and add them to the SET defined above
- If that SET contains items then create a list of SObjects and use 1 SOQL query to populate the entire list
- Now you can loop through the entire list of SObjects and make updates from there...
Below is an example of this in action:
if(trigger.isBefore){
//Set to hold the list of Contract Id's that will be queried for the associated Account
Set<String> ContractIds = new Set<String>();
//loop through all Agency Commission Records and add the Id of the Contract to the ContractIds Set
for(Agency_Commission__c ac : trigger.new){
if(ac.Contract__c != null){
ContractIds.add(ac.Contract__c);
}
}
if(!ContractIds.isEmpty()){
//Use a single query to pull a list of Contract SObjects
List<Asset_C__c> contractList = [select id, Account__c from Asset_C__c where id =: ContractIds];
//Map to hold the Contract ID as the Primary Key and the Account ID as the Key Value
Map<string, string> ContractAndAccount = new Map<string, string>();
//Loop through the List of Contracts and add the Contract ID and Account ID to the map
for(Asset_C__c c1 : contractList){
if(c1.Account__c != null){
ContractAndAccount.put(c1.id, c1.Account__c);
}
}
if(!ContractAndAccount.isEmpty()){
//Loop through the original Agency commission values and assign the Account based on the ContractAndAccount Map
for(Agency_Commission__c acUpdate : trigger.new){
//retrieve the Account from the ContractAndAccount Map and assign it to a string value
String acctForContract = ContractAndAccount.get(acUpdate.Contract__c);
acUpdate.Client__c = acctForContract;
}
}
}
}
Superb. Good explanation.
ReplyDeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
Deleteyes, nice explanation...
Delete