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
Sabrina Oliveira 3Sabrina Oliveira 3 

Apex: Getting history values from an object

Hi, guys!
I've created a "Retrieve" button in my object to return the Status value to the one before the one I am right now.

For example:
Status: Returned - Open - Starting - Writing - Completing - Closed
If I am at Writing and I need to go to the Returned, I'd like to go back to Writing after that just clicking the button.
It's working, the problem is that sometimes it updates to the Starting for example.
I can't understand why this happens and why this happens only sometimes. 
It is not a problem of permission or session, because I'm testing with Admin 

My code:
    public static String updateRecordAfterReturned(Id recordId){
        if (bankaccRcd == null){
            bankaccRcd = [SELECT Id, Status__c, Observations__c FROM Bank_Account_Request__c WHere Id =: recordId];    
        try {
            List<Bank_Account_Request__History> bar = new List<Bank_Account_Request__History>();
            bar = [SELECT ParentId, OldValue, NewValue, Field, CreatedById, CreatedDate FROM Bank_Account_Request__History 
                   WHERE ParentId = :recordId and Field = 'Status__c' LIMIT 1]; 
            bankaccRcd.Status__c = String.valueOf(bar[0].OldValue);
            update bankaccRcd;    
            return 'Success';
        }catch (DmlException e){
            Return 'Error: '+e.getMessage();
Best Answer chosen by Sabrina Oliveira 3
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sabrina,

The code looks fine . Unless some one updated the record there is no chance of getting it. Did you check the history related to that record by querring it with same query you used in apex.