Monday, October 28, 2019

TRIGGER.NEW AND TRIGGER.OLD IN APEX TRIGGER

Now that we understand that TRIGGER.NEW returns the new list of records and TRIGGER.OLD returns the old list of records, let's dive deeper into this concept with an example.

Scenario:
We will update the phone number of an Account record, changing it from a specific value to a new one. By using TRIGGER.NEW and TRIGGER.OLD, we will observe the old and new values of the phone number before and after the update is made to the record. This example will help us better understand how these trigger variables reflect changes during an update operation.

APEX TRIGGER:

Description:

The APEX Trigger AccountMainTrigger is fired before an update on the Account object. Within the trigger, it creates an instance of the createContactClass and calls the method1 to compare the old and new phone numbers of the Account records being updated.

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

APEX CLASS:

The class createContactClass defines method1, which takes two lists of Account records: one with new values (newList) and one with old values (oldList).

Method Logic:

The method loops through the newList to debug the new phone numbers.
Then, it loops through the oldList to debug the old phone numbers, allowing us to compare the values before and after the update.

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);
        }
    }
}

The image below shows the Account record in its initial stage, before any updates or changes have been made. It displays the original values of the Account fields as they exist at the start.

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