I want to enforce recalculation of all records in trigger.new and I want to do it in a "before" trigger:
trigger AnyTrigger on AnySObject__c (before insert, before update) {
Formula.recalculateFormulas( trigger.new );
}
This produces the following run-time exception
System.DmlException: Update failed. First exception on row 0 with id a0B0Y00000J4sjGUAR; first error: UNKNOWN_EXCEPTION, Cannot set the value of a calculated field: []
I checked the documentation here but it seems kind of poor and was not helpful.
I found this article here https://katiekodes.com/recalculate-formulas-salesforce-apex/ The workaround is to
- clone all the records of trigger.new and put the clones into a list
- execute Formula.recalculateFormulas() on the list of clones instead on trigger.new
- use the formulas from the clones to drive the logic on trigger.new
Even if it works, I don't like this approach. It costs memory and time and the triggers are already close to the limits and I need to keep the footprint as small as possible.
Questions
- is there any official documentation why we can't do this in a before-trigger context?
- is there a better workaround or a different approach to make the formulas recalculate in this example?