I have an object (call it "Details") with data that would look like this:
+------------+------------+-----------------------+
| Sequence # | % of total | Cumulative % of Total |
+------------+------------+-----------------------+
| 1 | 20 | 20 |
| 2 | 25 | 45 |
| 3 | 30 | 75 |
| 4 | 15 | 90 |
| 5 | 10 | 100 |
+------------+------------+-----------------------+
The users can only edit the "% of Total" column. So for example if I they edit sequence #3 to have a % of total like 25 (denoted by the **below), the results should look like this:
+------------+------------+-----------------------+
| Sequence # | % of total | Cumulative % of Total |
+------------+------------+-----------------------+
| 1 | 20 | 20 |
| 2 | 25 | 45 |
| 3 | **25** | *70 |
| 4 | *15 | *85 |
| 5 | *15 | *100|
+------------+------------+-----------------------+
I'm trying to perform the recalculation in an Apex trigger. In this example, the user updated the % of total for row 3 to 25%. The cumulative % of total for Seq. #3 needs to be updated, as do the % of total in rows 4 and 5, with the % of total for rows 4 and 5 being split evenly.
I can get the logic to work in a trigger. The way I have it now, I'm using two triggers: one before update, and one after.
- The before trigger updates row 3's cumulative % of total.
- When the after trigger runs, it updates the % of total on the next row, so in this case, row 4.
- That fires the before update trigger for row 4,which sets its cumulative % of total.
- The after trigger runs which updates row 5, which fires the before trigger.
The problem is that if there are too many rows, then I exceed the trigger depth. My first question: what's the best way to avoid this?
Or, alternatively, have I approached this completely wrong? I could probably do it all in an after trigger, but I'd probably end up with the same issue.