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
SupriyaH9SupriyaH9 

Controlling multiple recursive triggers in one transaction?

Little confused about the scope of a static variable here. I have 2 scenarios:
  • Two recursive trigger methods A and B in the same transaction - Does it mean will I need two static variables a and b to apply the recursion control for each one? And if this is true, does this mean I will need , e.g. 6 static variables doing the same thing to control 6 recursive methods in a single transaction? 😮
  • How does this scenario differ when I rather have 2 users instantiating the same transaction at the same time?
I went through the SF documentation and I couldn't get a clear idea on this. Any help on this would be greatly appreciated.
Dev KhatriDev Khatri
Hi Supriya,

There would be 2 transactions for 2 users, So static variables scope would be different for each user/transaction. Please see below salesforce documents.

"A static variable is static only within the scope of the Apex transaction. It's not static across the server or the entire organization. The value of a static variable persists within the context of a single transaction and is reset across transaction boundaries."

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm

Hope this help.

Thanks
SupriyaH9SupriyaH9
@Dev Khatri, what you said makes sense when 2 users instantiate the same class at the same time. But if the static variable is keeps it's state just for the transaction, is my first point right thinking I will need to maintain different static varibles for different recurring triggers in a single transaction?  
Dev KhatriDev Khatri
No, you don't need different static variables. Just wrap your trigger/helper code in that static variable. Make it true/false as per requirement it will maintain its value till that transaction get complete.  
SupriyaH9SupriyaH9
I just tested and verified this. You will need two different variables if you have two recursive methods in a single transaction. 
Because the static variable retains it's value for the scope of the transaction, for one method I will need the value of a static boolean true and for the other, I will need to be false - and in order to achieve this, I need to have 2 differnt variables. just one would not suffice. 
Dev KhatriDev Khatri
Yes @suriya you are right. It just depends on your requirement. let's suppose you have 5 methods in your trigger and you want to call only 3 methods in recursive then you can put them in single static variable based if block. 

More conditions need more static variables to control over them.

Thanks