How to write Bulk Triggers

The most common mistake people do with triggers is the assumption that triggers process one sObject record at a time. This used to be the case with earlier versions . In the present version, the single record processing model is no longer available. All trigger are bulk triggers by default, and can process multiple records at a time.

You need to know three things to write a bulk trigger:

1) Trigger Syntax
2) How to use Maps and Sets in bulk triggers
3) How to correlate records with query results


Trigger Syntax

trigger triggerName on ObjectName (trigger_events){

trigger testaccTrigger on Account (before insert, before update) {
// Your code here

Use Maps and Sets in Bulk Triggers

Maps – To hold query results organized by record ID
Sets – To isolate distinct records

trigger oppLineTrigger on OpportunityLineItem (before insert) {
Set<Id> pbeIds = new Set<Id>();

// Add distinct pricebook entries for every opportunity line item

for (OpportunityLineItem oli :

//Using the ID's stored in set (peIds) to query Pricebook entries

Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>( [select product2.color__c from pricebookentry where id in :pbeIds]);

//Use the Map to set appropriate color on every OpportunityLine item processed by trigger

for (OpportunityLineItem oli :
oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c;

Correlating Records with query Results

Use the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with query results.

//This trigger will prevent deletion of an opportunity which has a quote

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');

Happy Triggering!!!!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s