Skip to content

Instantly share code, notes, and snippets.

@oscartcy
Created May 27, 2015 08:06
Show Gist options
  • Select an option

  • Save oscartcy/5fae2ec73fdf2c057a3f to your computer and use it in GitHub Desktop.

Select an option

Save oscartcy/5fae2ec73fdf2c057a3f to your computer and use it in GitHub Desktop.
General trigger bulkification - best practices
Trigger myTrigger on Contact(before insert) {
map<Id,Account> accountMap = new map<Id,Account>();
for(Contact c : trigger.new){
accountMap.put(c.AccountId, null);
}
accountMap.remove(null);
accountMap.putAll([Select Id, Name, ShippingCity From Account Where Id In : accountMap.keyset()]);
for(Contact c : trigger.new){
if(accountMap.containsKey(c.AccountId)){
c.ShippingCity = accountMap.get(c.AccountId).ShippingCity;
}
}
}
Trigger myTrigger on Contact(before insert) {
for(Contact c : trigger.new){
if(c.AccountId != null) {
Account a = [Select Id, Name, ShippingCity From Account Where Id =: c.AccountId];
c.ShippingCity = a.ShippingCity;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment