Tuesday, 21 January 2014

Compare old and new values in trigger salesforce

We can compare old field value of records with the new values in trigger. Salesforce provides trigger.oldmap where in all the old records are stored in map with keyset as their id's. We can compare the old values with new values as in the below example.

Here, the trigger compares the account number old value with the new value. That is, trigger checks if the account number was changed.

If the account number is changed the trigger assigns the type field value "prospect" else it assigns it a value "Other" 

trigger Compare_OldandNewvalues on Account (before update) {

   for (Account acc: Trigger.new) {
        Account oldAccount = Trigger.oldMap.get(acc.ID);
        if(acc.AccountNumber != oldAccount.AccountNumber) {
           System.debug('--*Account Number is changed*--');
           System.debug('**Old Account Number :'+oldAccount.AccountNumber);
           System.debug('**New Account Number :'+acc.AccountNumber);
           acc.Type = 'Prospect';
        }
        else{
            System.debug('--**Account Number has not been Updated**--');
            acc.Type = 'Other';  
        }
    }
}

Also, note that the trigger.oldmap values can be accessed only in update and delete triggers and cannot be accessed in insert triggers.

No comments:

Post a Comment