You need to sign in to do that
Don't have an account?
Ankit Khiwansara 10
How can i bulkify below triiger
I have before insert trigger on the Lead object to fetch the Territory__c object, where the Territory__c.PostalCode__c matches the Lead.PostalCode. The code fails uses the Apex Data Loader to insert 10,000 Lead records.
code block:
for (Lead l : Trigger.new){
if (l.PostalCode != null) {
List<Territory__c> terrList = [SELECT Id FROM Territory__c WHERE PostalCode__c = :l.PostalCode];
if(terrList.size() > 0)
l.Territory__c = terrList[0].Id;
}
}
code block:
for (Lead l : Trigger.new){
if (l.PostalCode != null) {
List<Territory__c> terrList = [SELECT Id FROM Territory__c WHERE PostalCode__c = :l.PostalCode];
if(terrList.size() > 0)
l.Territory__c = terrList[0].Id;
}
}
Try the following code, it is working fine in my ORG and it may be helpful for you:
Trigger:
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha
All Answers
Try the following code, it is working fine in my ORG and it may be helpful for you:
Trigger:
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha
You need to read about trigger bulkification:
1. Never ever write a SOQL query inside any “for” loop. If you do that, your trigger is guaranteed to hit the governor limits.
2. Never ever perform a DML operation inside a “for” loop.
3. Do not fetch unnecessary data. Only fetch those fields and objects in your SOQL that you really require.
4. Always try to separate trigger and it's handler class.
5. In your code try to put null check conditions at every place where the record has the possibility to come null or undefined.
Follow this link also:
http://www.sfdc99.com/2014/01/18/bulkifying-code/
Try this code and change add conditions according to your requirement:
trigger:
trigger LeadTrigger on Lead (before insert) {
LeadTrigger_handler.fetchTerritory(trigger.new);
}
Handler class:
public class LeadTrigger_handler {
public static void fetchTerritory(List<Lead> leadList) {
try {
Set<String> leadPosttalcodeSet = new Set<String>();
List<Territory__c> terrList = new List<Territory__c>();
for(Lead l : leadList) {
if(l.PostalCode != null) {
leadPosttalcodeSet.add(l.PostalCode);
}
}
terrList = [SELECT Id FROM Territory__c WHERE PostalCode__c IN: leadPosttalcodeSet];
} catch (Exception ex) {
system.debug('Exception---ofLine--->' + ex.getLineNumber());
system.debug('Exception---Message--->' + ex.getMessage());
}
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi