0

I have a Trigger on an object, which is calling a method of other class(passing Trigger.New so that some functionality is executing depending on values of passed record) which should be called after insert, after update, after delete or after undelete of a record. I am using this trigger for rollup purpose, and cannot use standard salesforce rollup functionality for some reasons like no master-detail relationship.

This method is added to the trigger so that when the record is inserted or updated from Data Loader or from a Visualfore Page it should be executed and do some functionality depending on the values of the record.

Now from Visualforce I'm inserting a new record and updating another record(let's say Old record) of the same object in one transaction.

This object has some Workflow Rules and Process Builder flows created on it.

Now the issue is that this method is getting executed multiple times in same transaction since the new record is getting inserted(updated from WF and Process Builder), Old record is getting updated (updated once again from WF and process builder).

The method will execute for 4 times which is a cause for a governor error (SOQ) in my case.

Solution using to resolve:

  1. Create a static boolean variable(default:- false) and set it to true in VF controller.
  2. In trigger do not execute this method if the boolean variable is true(execute only if it is false:-for data loader).
  3. After completing all trigger operation (insert new record, update old record) in vf controller call that method and pass both records details(newly inserted and updated old record)so that it will be called only once in a complete transaction that to at the end of the transaction for updated values of New and old record.

Questions:

  1. Is above solution feasible or does this has any issues which you think of?
  2. Is there any other best approach to follow?
1
  • Am I reading this correctly to say that you hit a SOQL limit when a single method is executed four times in response to an insert of one record followed by 3 (?) updates? If so, it sounds like there is a bulkification issue in play as well.
    – David Reed
    Apr 16, 2018 at 13:14

1 Answer 1

1

Setting aside the fact you can implement rollups without Master-Detail relationship or writing any code yourself if you just use Declarative Lookup Rollup Summaries, you have one glaring problem with your approach. If you insert more than 200 records, your trigger will batch over them in multiple chunks, and for all but the first, your logic will be disabled.

If you want to do recursion prevention, a Boolean is basically never sufficient. You'll want Set<Id> instead. I would also recommend tracking each event separately if you wish to control all logic with this mechanism, for instance Set<Id> afterInsert, Set<Id> afterUpdate, etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .