+ Start a Discussion
Developer BaseDeveloper Base 

Trigger old and new value is identical

Hello, I have a code. I created fields on Account for trigger.old and trigger.new. They are always identical. How come?

The trigger works as a roll-up summary, but the values are not up-to-date when retrieving them via query.
 
trigger AggregateOrderAmount on Order (after insert, before update, after delete, after undelete) {
    Set<ID> setID = new Set<ID>();
    List<Account> lstAcc = new List<Account>();
    double val;
    for(integer i = 0; i<Trigger.New.Size(); i++){
        val = (trigger.new[i].TotalAmount - trigger.old[i].TotalAmount);
    }
    
    if(trigger.isinsert || trigger.isundelete){
        for(order o : trigger.new){
            setID.add(o.AccountId);
        }
    }
    else if(trigger.isDelete){
        for(order o : trigger.old){
            setID.add(o.AccountId);
        }
    }
    
    else if(trigger.isUpdate){
         for(order o : trigger.new){
            if(o.AccountId != null){
                if(trigger.oldmap.get(o.id).AccountId != o.AccountId){
                    setID.add(o.AccountId);     
                }
            } 
            setID.add(trigger.oldmap.get(o.id).AccountId);
         }
    }
    if(setid.size() > 0){
        lstAcc = [Select id,Order_Sum__c, val1__c, val2__c,(Select id,TotalAmount from Orders) from Account where id IN : setID];
    }
    for(Account acc : lstAcc){
        for(Order ord : acc.Orders){
            val += ord.TotalAmount;
                       
             for(integer i = 0; i<Trigger.New.Size(); i++){
            acc.val1__c = trigger.new[i].TotalAmount;
            acc.val2__c = trigger.old[i].TotalAmount;
    }                                        
        }
        acc.Order_Sum__c = val;
    }
    update lstAcc;
}

 
Developer BaseDeveloper Base
val1__c and val2__c are always the same. Why?