1

I need to a add formula field to SObject in Apex before the record is persisted.

Sobject.put(formulaFieldName, null) returns the error that the field is not editable.

I would need to run SObject.recalculateFormulas() and check the value in the formula field.

  • 7
    Formula fields are inherently read-only. As you found, you cannot write to them. They are calculated at the time of display or query. If you want to calculate and populate the field in code, then it should be a different field type. Can you edit your question to add some detail about what you're trying to accomplish, ie, why you want to write to the field rather than letting the fornula do its job? And why SObject.recalculateFormulas() is apparently not a good solution for you? – Thomas Taylor Jun 22 at 0:02
  • Even if I execute SObject.recalculateFormulas() I would expect that the framework wisely add a formula field to the SObject but it does not. I need to display formula field to a user before the record is actually saved. – Andrew Jun 22 at 12:38
  • recalculateFormulas() doesn't work on. cross-object formulas - is that the case here? – Thomas Taylor Jun 22 at 14:17
  • yes, it is cross-object formula – Andrew Jun 22 at 20:36
2

Formula fields are inherently read-only. As you found, you cannot write to them.

SObject.recalculateFormulas() doesn't recalculate cross-object formulas. From the documentation:

This method doesn’t recalculate cross-object formulas. If you call this method on objects that have both cross-object and non-cross-object formula fields, only the non-cross-object formula fields are recalculated.

You're probably going to need to recalculate the value in Apex yourself to present it to the user before saving. Without more information about the requirements and what UI you need to present this in, it's not possible to give guidance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.