0

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?
Uwe Heim
  • 28,350
  • 18
  • 115
  • 283
  • I linked an older version of the question, it's got some history. As far as we outsiders know, it's a bug. This is particularly telling, because you're getting an UNKNOWN_EXCEPTION rather than a more specific exception that would happen (QueryException, DmlException, something). The workaround is the best that you can reasonably do. You may want to report this as a bug, though, but I'll ask for clarification from on high, just to be sure. – sfdcfox Nov 03 '21 at 18:33
  • Bug W-10128616 was created for you. If you want to open a case, reference that number. – sfdcfox Nov 04 '21 at 01:10
  • 1
    I've taken it a step further as well can had a Known Issue created so you can skip the bug step https://trailblazer.salesforce.com/issues_view?id=a1p4V000002CEn8QAG – Daniel Ballinger Nov 09 '21 at 16:59

0 Answers0