This post is the continuation of my previous post
“Bulkify Your Code” – Explanation of Salesforce’ Governor Limit with Use Case
Use Case –
I have two custom objects (Airport__c and Country__c). Below screenshot will give you field details.
My requirement is to make sure when I am inserting an Airport record, I need to check whether the country mentioned in the record is already present in the Country object, if not, then create a new Country record with name same as mentioned in the Airport’s Country field provided that Aiport is operational i.e. Operational__c == true.
Solution –
Initially it may look like the requirement is very easy to implement. But we need to keep in mind the Salesforce’s Governor Limit.
If we go ahead with the approach of iterating over each new Airport record and then do a query against Country object to check whether that country is already there in the system, we will quickly hit Salesforce’s Governor Limit – “Total number of SOQL Issued – 100 (Synchronized) and 200 (Asynchronized)”.
So we need to make sure that our code is efficient. Below is the optimized trigger which can handle the requirement and at the same time will make sure that we will not hit by Governor limit.
trigger AirportTrigger on Airport__c (after insert) {
List<Country__c> allCountries = new List<Country__c>();
List<String> allCountryNames = new List<String>();
//Fetch all Country Name and put it into a list - SOQL# 1
for(Country__c aCountry : [SELECT ID, Name FROM COUNTRY__C]){
allCountryNames.add(aCountry.Name);
}
//Iterate only those Airport records matching the requirement - SOQL# 2
for(Airport__c anAirport : [SELECT ID, Country__c, Operational__c from AIRPORT__C where ID IN :Trigger.new
AND Country__c NOT IN :allCountryNames]){
if(anAirport.Operational__c){
Country__c aCountry = new Country__c(
Name=anAirport.Country__c
);
allCountries.add(aCountry);
}
}
//Do a bulk insert
if(allCountries.size() > 0){
Database.insert(allCountries);
}
}
The above code is very much self-explanatory. Please let me know if you need any help. Thanks.