function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kamaldeep SehrawatKamaldeep Sehrawat 

How to bulkify and batchify a trigger to avoid Governance Limits

Hi All, 

I am very new to Apex and trying to bulkify and batchify a trigger to avoid the Governance Limits. Below is the my trigger


trigger IAA on Contact (before insert, before update)
{
for (Contact c : Trigger.new)
{
    if  (c.Area_of_Interest_del__c != 'Law' && (c.Visa_Type__c == 'J1 Exchange Visitor'||c.Visa_Type__c =='F1 Nonimmigrant Student'||c.International_Student__c ==True))
    {
        Account iaa = [Select Id FROM Account WHERE Account.Name = 'GGU - International Admissions & Advising'];
        c.AccountId = iaa.Id;
    }
}
}


I will really appreciate any help. 

Thanks 
Best Answer chosen by Kamaldeep Sehrawat
Vamsi KrishnaVamsi Krishna
one simple step is to move any DML statements out of the loops..
in your case, since you are going to use the same account on all contacts matching a condition, you dont need to query the account again & again in the loop.. just query it once at the begining and use it..

trigger IAA on Contact (before insert, before update)
{
Account iaa = [Select Id FROM Account WHERE Account.Name = 'GGU - International Admissions & Advising'];
for (Contact c : Trigger.new)
{
    if  (c.Area_of_Interest_del__c != 'Law' && (c.Visa_Type__c == 'J1 Exchange Visitor'||c.Visa_Type__c =='F1 Nonimmigrant Student'||c.International_Student__c ==True))
    {
            c.AccountId = iaa.Id;
    }
}
}

for more details on how to bulklify your code, refer this article
http://wiki.developerforce.com/page/Best_Practice%3A_Bulkify_Your_Code

All Answers

Vamsi KrishnaVamsi Krishna
one simple step is to move any DML statements out of the loops..
in your case, since you are going to use the same account on all contacts matching a condition, you dont need to query the account again & again in the loop.. just query it once at the begining and use it..

trigger IAA on Contact (before insert, before update)
{
Account iaa = [Select Id FROM Account WHERE Account.Name = 'GGU - International Admissions & Advising'];
for (Contact c : Trigger.new)
{
    if  (c.Area_of_Interest_del__c != 'Law' && (c.Visa_Type__c == 'J1 Exchange Visitor'||c.Visa_Type__c =='F1 Nonimmigrant Student'||c.International_Student__c ==True))
    {
            c.AccountId = iaa.Id;
    }
}
}

for more details on how to bulklify your code, refer this article
http://wiki.developerforce.com/page/Best_Practice%3A_Bulkify_Your_Code
This was selected as the best answer
Vamsi KrishnaVamsi Krishna
Kamal,
let me know if it solved ur issue or if you have any more queries..
Kamaldeep SehrawatKamaldeep Sehrawat
Vamsi, 

Thanks for your help. It works. 

Kamaldeep
Vamsi KrishnaVamsi Krishna
glad it worked. please mark it a best answer to make this a solved one