function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
abhishek singh 497abhishek singh 497 

to compare old and new value of formula field in apex trigger

Hello Team,
I have one requirement where I need to compare old and new value of formula field in apex trigger.
Anyone has any suggestions or code please let me know.

Thanks 
Naveen KNNaveen KN
Hi Abhishek, Verified this in our developer edition. 

In this example we have created two number fields and one formula field to store the total of number field 1 and number field 2User-added image

Old set is 10+12= 22 and the new set is 12+12 = 24, Total is the formula field which adds Number1 and Number2 

User-added image

So, the old value of formula field is 22 and the new value is 24. The same can be found in the logs 

 User-added image
Trigger code goes here:
trigger CaseDemoTrigger on Case (before update) {
    list<case> newList = trigger.new;  
    list<case> oldList = trigger.old; 
    system.debug('oldList formula fied value is' + oldList[0].Total__c);
    system.debug('newList formula field value is' + newList[0].Total__c);
}
Modify the code based on your requirement. Share the results here. 

Team codegine!



 
Deepali KulshresthaDeepali Kulshrestha
Hi abhishek,
No, you cannot compare two formula field values in Apex triggers as it will not bring any changes after trigger execution as you are trying to compare fields that are of formula type.

Please go through the helpful links provided below:
https://salesforce.stackexchange.com/questions/8100/do-apex-triggers-have-access-to-formula-fields
https://success.salesforce.com/answers?id=9063A000000p6rrQAA

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
Naveen KNNaveen KN
Hi Deepali, here the requirement is to compare the old and new value of any formula field in the trigger, which is acheivable as mentioned above. 
abhishek singh 497abhishek singh 497
Hello Codengine,
I missed one thing in my question , I need to run trigger also on basis of formula field.