Activity › Forums › Salesforce® Discussions › Trigger in salesforce
-
Trigger in salesforce
Posted by madhulika shah on August 30, 2018 at 1:28 PMHow to restrict any Trigger to fire only once OR how we can avoid repeated or multiple execution of Trigger?
shariq replied 7 years, 9 months ago 3 Members · 2 Replies -
2 Replies
-
Hi Madhulika,
You need to add one Static Boolean variable to a your utility/helper class (any apex class), and check its value within affected triggers, where you do think this trigger will get fired more than once.
“MyUtilityClass” is your helper / utility apex class where we will have our static boolean variable – e.g. declared as “runOnceFlag= true”
public class MyUtilityClass {
public static boolean runOnceFlag= true;
}Sample example Trigger – where you will check for the value of static boolean variable “runOnceFlag”- For first time its value will be equal to TRUE, and we will set its value to FALSE in our trigger to avoid second run.
trigger myTriggerName on Account (before delete, after delete) {
if(Trigger.isBefore && Trigger.isDelete){
if(MyUtilityClass.runOnceFlag){
MyUtilityClass.runOnceFlag=false; }
}
} - [adinserter block='9']
-
Hi,
Try this –
Class code
public class checkRecursive {
public static Set<Id> SetOfIDs = new Set<Id>();
}In order to avoid the situation of recursive call, make sure your trigger is getting executed only one time. To do so, you can create a class with a Static Set
Check if the record exists in the set, if so do not execute the trigger, else execute the trigger.
NOTE: Before deploying into production, we recommend testing in sandbox.
This is a sample code written for Account object Class code
public class checkRecursive {
public static Set<Id> SetOfIDs = new Set<Id>();
}
Trigger code
trigger TestTrigger on Account (before insert) {
if (Trigger.isAfter && Trigger.isInsert) {
List<Account> accList = new List<Account>();
for (Account test: Trigger.new) {
If(!checkRecursive.SetOfIDs.contains(test.Id)){
test.Name = ‘helloworld’;
accList.add(test);
checkRecursive.SetOfIDs.add(test.Id);
}
}
insert accList;
}
}Hope this helps.
Log In to reply.