5

I have a custom formula field on Contact which refers Account field. I want to get the value of that formula field before doing any insert operation, how can I do this?

I tried using recalculateFormulas() method but its always returning null.

Here is the code which I tried.

Contact conObj = new Contact();
conObj.LastName='Last';
conObj.AccountId = '001f100001NKm4t';
conObj.recalculateFormulas();
system.debug('>>> conObj... '+conObj.Account_Completed__c);
1
  • 1
    is it cross object formula? recalulate formyla doesnt work on cross object formulas May 11, 2018 at 9:21

1 Answer 1

5

recalculateFormulas() 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.

Each recalculateFormulas call counts against the SOQL query limits. See Execution Governors and Limits.

As recalculateFormulas already consumes a SOQL, why not do a dummy dml and requery the cross object fields.

You can do a dummy insert to see cross object referenced values via SOQL and then rollthem back if not needed.

public static Contact dummyInsertContact(Contact con){
    Savepoint sp = Database.setSavepoint();
    upsert con;

    Contact newCOn = [Select id,Name, Account_Completed__c from Contact where Id =:con.Id];

    Database.rollback(sp);
    con.Id=null;
   return newCOn;

}

And then your main code will be

Contact conObj = new Contact();
conObj.LastName='Last';
conObj.AccountId = '001f100001NKm4t';
Contact dumCOntac = dummyInsertContact(conObj);
system.debug('>>> conObj... '+dumCOntac.Account_Completed__c);
1
  • It seems even not working for normal formula fields like: CASE( MOD(TODAY() - DATE(1900, 1, 7), 7), 0, 'Sunday', 1,'Monday', 2,'Tuesday', 3, 'Wednesday', 4, 'Thursday', 5, 'Friday', 'Saturday' ) May 12, 2018 at 18:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .