Bulkify code to sit within the governors' limits.
- johnsontitus
- May 9, 2020
- 2 min read
Updated: May 10, 2020
use case:
When a contact is inserted or updated, its field State__c should be updated
with the state where its postal code matches with the state's postal code.
contact has a look up relation to state.
trg on Contact(before insert, before update){ List<String> pcode = new List<String>(); for(Contact cnt : Trigger.new){ pcode.add(cnt.PostalCode); } //create Postal Code to ID map Map<String, Id> states = new Map<String, Id>(); //SOQL query is performed once outside the for loop //results are stored in a map for(State__c s : [select id, Postal__c from State__c where Postal__c in :pcode]){ states.put(s.Postal__c, id); } List<State__c> stateList = new List<State__c>([select Id,Postal__c from State__c where Postal__c in :pcode]); // create list to store contact for updating List<Contact> contactsToUpdate = new List<Contact>(); for(Contact cnt : Trigger.new){ if(con.PostalCode != null){ //State Id is extracted from the map //instead of performing a SOQL query String stateId = states.get(con.PostalCode); if(String.isNotBlank(stateId){ cnt.State__c = stateId; contactsToUpdate.add(cnt); } } } update contactsToUpdate; }
use case:
every tiem a record on contact with isPrimaryContact is set to true is deleted, its related account record should be updated by setting its field hasPrimaryContact to false.
trigger trgContact on Contact (after delete){
//1. declare a set for storing id(s) of the related records
Set<id> accountIdListToUpdate = new Set<Id>();
//2. retrieve the related records' id using the Trigger context variable
//and store them in the set for id(s).
if(Trigger.isAfter && Trigger.isDelete){
for(Contact con : Trigger.old){
accountIdListToUpdate.add(con.AccountId);
}
}
//3. declare a list for collecting the related records to be updated
List<Account> accountsToBeUpdated = new List<Account>();
//4. retrieve the related records by using the soql and set for id(s) for filtering
// and store them in the list declared for storing the records
accountsToBeUpdated = [select Id, hasPrimaryContact from Account where id = :accountIdListToUpdate];
//5. iterate through the records to be updated and update them
for(Account acct : accountsToBeUpdated){
acct.hasPrimaryContact = false;
}
//6. finally outside the loop call the dml statement
update accountsToBeUpdated;
}

Comments