Recalculate Formula Fields without DML Statement

Sometimes we need to show output of formula in UI. when I say UI, it can be either via Visualforce Pages, Lightning Components or Lightning Web Components. Traditionally to get the formulas calculated, DML needs to be performed for the objects. Since winter 20 release, Salesforce has provided callability to auto calculate formulas without performing DML operation.

Scenario

We have a custom formula field “Opportunity_Serial_Number__c” on opportunity line item to show opportunity Serial Number, We have following apex code:

private void showTotalAmountOnOLI(id OppId, id PBEId) {
	List<OpportunityLineItem> OLIs = new List<OpportunityLineItem>();
        OLIs.add(new OpportunityLineItem(OpportunityId = OppId, PricebookEntryId = PBEId, UnitPrice = 100, Quantity = 10));
        Formula.recalculateFormulas(OLIs);
        system.debug(OLIs[0].Opportunity_Serial_Number__c);
}

Explanation

  • We have showTotalAmountOnOLI method accepting OppId (Opportunity Id) and PBEId (Pricebook Entry Id).
  • Initialized list of opportunity with one line item providing opportunity id and pricebook entry id.
  • Without writing an insert DML statement, we forced recalculation of all formula fields for the records passed in function recalculateFormulas();
  • Syntax of function is Formula.recalculateFormulas(list<sObject>). More information can be found here.
  • After recalculating the formulas, Opportunity Serial Number printed with debug statement.

This is just an explaination how recalculating works, however this is very much needed when showing output of formula field on visualforce page without saving a record.