Why the future method calls 2 times in update?

Posted on

While, I was working on one of my clients project, I came across a bizarre scenario. That was, when I updated a custom object named “product config”, it was calling the update trigger twice, which resulted 2 future calls eventually.

The problem was, whenever the user updates the record (product config), the update was calling the update trigger to perform the required action. Since the record is updated through trigger, it calls the trigger twice – first when the user updates the record, and then again by the code in the trigger, so the @future is calling another @future during the second update.

To get rid of this, I have written a class, which contains a Boolean variable to prevent the trigger is being called again. It looks like the following code,

Public with sharing  class updateHelper{

Public static Boolean val=false;

Public static void preventRecursive(Boolean b){

Val=b;

}

}

The above code sets the val to false initially and it is checked in the beginning of update trigger to prevent the second pass. In the trigger the initial check of the Boolean is done and then it is set to true inside. The trigger code looks like,

If(!updateHelper.b){

updateHelper.preventRecursive(true);

//action codes

}

So, eventually, it called the @future method once and updated the product config once.