0

I have a VF page in which I load an account on the page load. I've created a static variable to save the loaded account in to, in order to compare whether any changes were made on the page as I need to take different actions depending on what was changed.

On initial load of the page it populates the Account object and the oldAccount object variable and then displays the page. I make some edits and then click a Next button, which goes through a validate method to check on what changes were made on the page. Here's where I want to compare what was in the old account and what's on the page (the page uses the account fields as input). I made the oldAccount variable static so it doesn't clear it, but when I click on the Next button, the oldAccount is null. Why is this? How do I keep the original loaded Account values to compare to what's entered on the VF page?

public Account account { get; set; }
public static Account oldAccount { get; set; }

public AccountPageController(){
    accountId = ApexPages.CurrentPage().getParameters().get('id');
    account = queryAccount(accountId); \\ gets the account from the parameter passed to the VF page
    if(oldAccount == null){
       oldAccount = account; \\ on loading the page initially, it sets it correctly here
    } 
 .....
}

......
public PageReference pageAccountNext() {
   if (validateAccount()) {
      saveAccount();
   }
}

public Boolean validateAccount() {

   system.debug(account: ' + account);
   system.debug(oldAccount: ' + oldAccount); // when I get here it's null - why?
 ..... code to compare old to what was entered on the VF page and set flags accordingly
}
1

Static variables are cleared on each transaction start. Instead, you'd make the variable non-static, which would place the account in the view state. However, I would point out that other users may have made edits between page load and saving, so you may want to just query the record from the database anew and then do your validations. This ensures that any concurrent edits would be taken into account.

If the view state size is of any concern, serialize the data and place it in a hidden input field, which you would then bind to the controller:

static Account oldAccount;
public static String oldAccountJson {
  get { return JSON.serialize(oldAccount); }
  set { oldAccount = (Account)JSON.deserialize(value, Account.class); }
}

...

<apex:inputHidden value="{!oldAccountJson}" />
1
  • Thanks - I queried the data again to do the compare & that works :) – Irene Jun 3 '20 at 0:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.