Salesforce Apex Trigger | Part 2

Salesforce Apex Trigger Part 2

In the previous EPISODE, We have discussed Before Insert and After Insert.
In this Episode, we will discuss Update Events in Salesforce.
So let's get started
Update Events In Salesforce 

There are two update events in Salesforce :
1. Before Update 
2. After Update

Trigger.old and Trigger.New is used in update events in Salesforce.
Let's consider, we have a customer object with the following records
Customer (Object):

| CID | Name | Age | Phone |
----------------------------------
| 111 |  aaa   |  23   | 3455  |
| 222 |  bbb   |  34   | 2344  |
| 333 |  ccc    |  45   | 9876  |
| 444 |  ddd   |  27   | 2346  |
----------------------------------

In the above table when we are trying to update the records we will use 
| 333 |  ccc    |  45   | 9876  | - TO - | 333 |  ccc    |  29   | 7654  |
| 444 |  ddd   |  27   | 2346  | - TO - | 444 |  ddd   |  35   | 1234  |

Trigger.New :
Trigger.New will store the set of records with new values on which you are performing the update operation.

i.e., Trigger.New will have 
| 333 |  ccc    |  45   | 7654  |
| 444 |  ddd   |  27   | 1234  |

These are records which will store into Trigger.New
Trigger.Old :
Now, on the other hand, Trigger.Old will store the set of records on which we are performing the update operation.

Trigger.Old will store the records with old values.
i.e., In the above case Trigger.Old will have 
| 333 |  ccc    |  45   | 9876  |
| 444 |  ddd   |  27   | 2346  |  

Now let's understand what will happen when an event fire
Event: Before Update :
Whenever we are trying to update any records in the object. The operations which need to be performed before saving the changes to the database are written in before update.
For Example :
=============================================
Customer (Object)

| CID | Name | Age | Phone |
----------------------------------
| 111 |  aaa   |  23   | 3455  |
| 222 |  bbb   |  34   | 2344  |
| 333 |  ccc    |  45   | 9876  |
| 444 |  ddd   |  27   | 2346  |
----------------------------------

Step 1 :
  • Update last 2 records as
| 333 |  ccc    |  29   | 7654  |
| 444 |  ddd   |  35   | 1234  |

Step 2 :
  • Before update operations are performed.
Step 3 :
  • Newly updated records are
| CID | Name | Age | Phone |
----------------------------------
| 111 |  aaa   |  23   | 3455  |
| 222 |  bbb   |  34   | 2344  |
| 333 |  ccc    |  29   | 7654  |
| 444 |  ddd   |  35   | 1234  |
----------------------------------
=============================================

When we modify the value of a record and click on update.

Before the trigger will be called on an object and all the operation which is written, it will be performed.

Records are updated with new values in the database.
NOTE: If we want to make any changes in the values of a new record we can directly perform using Trigger.New in before trigger.

We cannot perform any changes in the records that are in Trigger.New using DML operations as they are not at committed in before update.

Event: After Update : 

The operations are written in the after update trigger will be fired when the changes that we have done are saved to the database.
For Example :
=============================================
Customer (Object)

| CID | Name | Age | Phone |
----------------------------------
| 111 |  aaa   |  23   | 3455  |
| 222 |  bbb   |  34   | 2344  |
| 333 |  ccc    |  45   | 9876  |
| 444 |  ddd   |  27   | 2346  |
----------------------------------

Step 1 :
  • Update last 2 records as

| 333 |  ccc    |  29   | 7654  |
| 444 |  ddd   |  35   | 1234  |

Step 2 :

| CID | Name | Age | Phone |

----------------------------------
| 111 |  aaa   |  23   | 3455  |
| 222 |  bbb   |  34   | 2344  |
| 333 |  ccc    |  29   | 7654  |
| 444 |  ddd   |  35   | 1234  |
----------------------------------
  • Operations wrote in after update performed now on a new set of data.
=============================================
As you can see there are the above operation is performed in only in 2 steps.
When we make some changes on records of the object and click on update.
First, before trigger operations are performed on the object.
Then after completion, Before update operations all values in Trigger.New are updated to object.
Once records Trigger.New are updated to object then After trigger operations are performed.
NOTE: In the after update trigger operations we can only read the data from the trigger.
  • If we want to perform any changes on the records in after update triggers we have to write DML Statements.
  • Now let's talk about some scenarios to understand this perfectly
Scenario 1 :
Whenever Customer record is updated, before updating the record create a new record in test object with old values of the customer record.
=============================================
trigger CustomerUpdate on Customer__c (before update)

{

    List<Test__c> test = new List<Test__c>();

    for(Customer__c x: Trigger.old)

    {

     Test__c t = new Test__c();

     t.Name = x.Name;

     t.salary__c = x.salary__c;

     t.phone__c = x.phone__c;

     test.add(t);

    }

  insert test;
}
=============================================

Scenario 2 :
To update the owner of a case based on the values selected within a picklist and populate the owner field with the created by field data. When we have selected any FieldName = Status

Picklist values are = 
                             priced - (Initial)
                             priced - (Re-priced)
                             priceFile Loaded
=============================================
trigger CaseTrigger on Case(before update)
{
    for(Case c : Trigger.New)
    {
     If(c.Status == 'priced - (Intial)'
     || c.Status == 'priced - (Repriced)' 
     || c.Status == 'priceFile Loaded')
     {
         c.owenerId = c.createdById;
     }
    }
}
=============================================

Scenario 3 : 
Write a trigger that will prevent a user from creating a lead that already existed as a Contact.  We'll use the lead/contacts email address to detect duplicates. Whenever the lead is created or updated.
1. Lead has an email address 
2. Try to find a matching contact based or email address.
3. If a match is found, give the user an error.
4. If a match is not found, do nothing.
=============================================
trigger FindDup on Lead (before insert, before update)
{
    for(Lead myLead : trigger.New)
    {
     if(myLead.Email != null)
     {
      List<Contact> dupes = [SELECT Id FROM Contact WHERE Email = :                                                  myLead.Email];
      if(dupes! = null && dupes.size() >0)
      {
          String errorMessage = 'Duplicate Contact Found !!';
          errorMessage + = 'Record ID is' + dupes[0].Id;
          myLead.addError(errorMessage);
      }
     }
    }
} 
=============================================
So guys In this way we can use and write update trigger based on the different scenarios.
In this episode, we discussed the execution of the update trigger as well as when we can use trigger.Old or trigger.New.
In the Next EPISODE, we will talk about Delete trigger events in Salesforce so stay Tuned......
WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE APEX TRIGGER PART 2 EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)

<< PREVIOUS                                                       NEXT >>


salesforce kid on google play store
Salesforce Apex Trigger | Part 2 Salesforce Apex Trigger | Part 2 Reviewed by on Rating: 5

2 comments:

  1. Hi There,
    I just started learning Salesforce development(preparing for pd1). I did not get triggers quite well. Your explanation is excellent. please post articles like this on web components and LWC as well. Thank you for doing this for people like me, who can't effort to pay for tuition.

    ReplyDelete
    Replies
    1. Hello,

      Thanks for your kind words. Glad to know that these blogs are helping you to learn new things.

      Surely, I will put more blogs like this.

      Thank you once again.

      Best Regards,
      Ajinkya

      Delete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.