Monday, October 28, 2019

TRIGGER.NEW AND TRIGGER.OLD IN APEX TRIGGER


So now we have understood that trigger.new returns new list of records and trigger.old returns old list of records. Let us try to understand the same again by taking an example.

SCENARIO: We are going to update the Account record phone number from a particular value to a new value and we will using trigger.new and trigger.old to see the old and the new value before and after the update is done to a record.

APEX TRIGGER:

trigger AccountMainTrigger on Account (before update) {
    createContactClass obj=new createContactClass();
    if(trigger.isbefore && trigger.isupdate)
    {
     obj.method1(trigger.new,trigger.old);
    }
}

APEX CLASS:

public class createContactClass {
    public void method1(List<Account> newList,List<Account> oldList){
        for(Account obj:newList){
            system.debug('New Value of phone'+obj.phone);
        }
        for(Account obj1:oldList){
            system.debug('Old Value of phone'+obj1.phone);
        }
    }
}

Account record in the initial stage,

how to compare old value and new value in apex class

Now let us update the phone number on the Account record.

compare trigger.old and trigger.new values

Now go to “Developer console” as shown in the below image to check the debug values,

what is trigger.old and trigger.new in salesforce

2 comments:

  1. Any code is added in open execute anonymous window. for checking debug logs

    ReplyDelete
    Replies
    1. No code is added in execute anonymous window, System.debug in code will be displayed under log.

      Delete