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
aj2taylo2aj2taylo2 

Apex Class - Compare Old vs. New Values

I have a custom class that is updating a list of records.

 

Is there a way for me to iterate through the list to determine if a particular field has been updated before/after update?

 

public PageReference mySave() { 
    update this.myRecords;

    for(Object__c o : this.myRecords) 
        if(o.myField__c <> [oldvalue].myField__c)
            {do something}
}

 

I know how to accomplish this in a trigger, but I only want to execute this change check within my controller, not globally for all record updates.

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

If you want it done only in a Visualforce page, you'll just need to clone the original record:

 

public with sharing myControllerClass {
  SObject[] oldRecords;
  ApexPages.StandardController con;

  public SObject[] myRecords;

  public myControllerClass(apexpages.standardcontroller controller) {
    // Populate myRecords first
    oldRecords = myRecords.deepClone(true,true,true); // Copy
  }

  public ApexPages.StandardController mySave() {
    update myRecords;
    for(Integer i = 0;i < myRecords.size();i++)
     if(myRecords[i].myField__c != oldRecords[i].myField__c)
       { do something }
  }

 

All Answers

Rahul_sgRahul_sg

I've not gone through your detailed requirement however....you can use Trigger.old & Trigger.new....by calling this class from trigger.

 

OR 

If requirement can be achived by writing a Validation/WF formula...you can use priorvalue() function

sfdcfoxsfdcfox

If you want it done only in a Visualforce page, you'll just need to clone the original record:

 

public with sharing myControllerClass {
  SObject[] oldRecords;
  ApexPages.StandardController con;

  public SObject[] myRecords;

  public myControllerClass(apexpages.standardcontroller controller) {
    // Populate myRecords first
    oldRecords = myRecords.deepClone(true,true,true); // Copy
  }

  public ApexPages.StandardController mySave() {
    update myRecords;
    for(Integer i = 0;i < myRecords.size();i++)
     if(myRecords[i].myField__c != oldRecords[i].myField__c)
       { do something }
  }

 

This was selected as the best answer
aj2taylo2aj2taylo2

Thanks sfdcfox;  someone else suggested this to me as well, and it got me the result I wanted!