Tuesday, 24 May 2011

Writing Apex Trigger : Issues and Solutions ( Bulk Upload )

Hi All,

I have been facing issue of exceeding limit even though applying every possible optimizing tech. that we discussed in earlier posts. This case is more often if not always is trigger invocation on bulk upload of records. Now to avoid such situations use a Static Variable on the start of trigger. And on action of bulk upload set this static variable to false.
Create a Class with Static Variable
public class Constants
    {
         //Constant to block execution of trigger
         public static Boolean runTrigger = true;
    }
trigger <name> on Account (<events>) 
    {
        if(Constants.runTrigger)
            {
                //logic to be executed by trigger
            }
    }
Now we should set static variable to false
public class BulkUpdateClass
    {
         //Method to do trigger event on bulk of records
         public void triggerBulkUpdate()
               {
                    //Set static variable to false
                    Constants.runTrigger = false;

                    //Bulk Update Action Logic
               }
    }

By this we can stop execution of trigger for bulk of records

Regards

2 comments:

  1. Hello again,

    On the forums, I see where you used a static map instead of Boolean static. The link on the boards is: http://boards.developerforce.com/t5/Apex-Code-Development/trriger-problem/td-p/325603/highlight/false

    But the comments were "this trigger will not work for ol2 thats why I took Id of record in set. And when you will update and insert at same time then also it will not work. Let me know if i you did not get my point. I have done a POC on using static variable in trigger and it does not work in some cases."

    Could you expand on why and when to use a Boolean vs. a set?

    Thanks!

    ReplyDelete

Tweet