Friday, June 1, 2012

Best Practices of Triggers


Use Set & Map wherever applicable
Code:
// for every OpportunityLineItem record, add its associated price book entry to a set so there are no duplicates.
trigger oppLineTrigger on OpportunityLineItem (before insert) {
Set pricebookIds = new Set();
for (OpportunityLineItem oli : Trigger.new)
pricebookIds.add(oli.pricebookentryid);
// Query the PricebookEntries for their associated product color and place the results in a map of price book entery.
Map entries = new Map( [select product2.color__c from pricebookentry where id in :pbeIds]);
// Now use the map to set the appropriate color on every OpportunityLineItem processed by the trigger.
for (OpportunityLineItem oli : Trigger.new)
oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c;
}
Correlating Records with Query Results in Bulk Triggers
• Use the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with query results
trigger oppTrigger on Opportunity (before delete) {
for (Quote__c q : [select opportunity__c from quote__c where opportunity__c in :Trigger.oldMap.keySet()])
{
Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete opportunity with a quote');
}
}

No comments:

Post a Comment