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
MyGodItsColdMyGodItsCold 

Is there a small code example of using History's OldValue or NewValue in an APEX if statement?

I am running a SOQL against AccountHistory. I am then looping through the resultant list and testing to see if an OldValue equals  something. I can't save the code and get an error: 

 

Save error: Illegal assignment of SObject to string

 

Does anyone have a code snippet showing how to use OldValue, NewValue? I read where they are "Any Type" ...

 

 

Apex Manual Reference

Thanks in advance...

 

Best Answer chosen by Admin (Salesforce Developers) 
Jia HuJia Hu
try this

List<AccountHistory> ahlist = [Select Id, Field, NewValue, OldValue From AccountHistory];
for(AccountHistory ah:ahlist) {

if( (ah.OldValue != null) && (String.valueOf(ah.OldValue)).equals('string to filter') ) {
System.debug(' ---------------- ' + ah.Field + ah.NewValue + ah.OldValue);
}
}

All Answers

Jia HuJia Hu
try this

List<AccountHistory> ahlist = [Select Id, Field, NewValue, OldValue From AccountHistory];
for(AccountHistory ah:ahlist) {

if( (ah.OldValue != null) && (String.valueOf(ah.OldValue)).equals('string to filter') ) {
System.debug(' ---------------- ' + ah.Field + ah.NewValue + ah.OldValue);
}
}
This was selected as the best answer
vishal@forcevishal@force

Hope this helps and clears your doubt.

 

 

List<CaseHistory> lst = [Select field, oldValue, newValue from CaseHistory];
for(CaseHistory c : lst)
{
    /*
    This gives illegal assignment from object to string
    String old = c.oldValue;
    String newVal = c.newValue;
    String field = c.field;
    */
    
    // you need to convert them
    // direct typecasting doesn't work because old value and new value can be any type and not all types are supported.
    String old = String.valueOf(c.oldValue);
    String newVal = String.valueOf(c.newValue);
    String field = String.valueOf(c.field);
    system.debug(' ##### The value on ' + field + ' has been changed from ' + old + ' to ' + newVal);
}

MyGodItsColdMyGodItsCold

Thank you for responding. This works also.