| by Arround The Web | No comments

Salesforce Apex – Triggers

In Salesforce, validating the data before/after insertion is very important and should be taken into consideration. In most of the scenarios, after entering the data into the Salesforce object, some data manipulation needs to happen and wrong insertions/deletions/updates have to be validated and handled. To achieve this, Salesforce introduced an Apex script which is known as “Trigger”. Quickly dive into the guide that deals with trigger events, context variables, types and scenarios with real-time examples.

Apex Trigger

In Salesforce, trigger is an Apex-Code (.apxt) that fires before or after the data manipulation instances. Based on the event that is specified in the trigger, it fires on specified objects in Salesforce. Also, we can specify the contexts that help us to access the run-time contexts. This helps us to prevent unwanted/unnecessary actions on objects in Salesforce. Say, in the account object, we need to update only the phone when the “industry” is “Agriculture”.

Trigger Events

As we already discussed, a trigger fires before or after the DML operations occur.  There are three DML operations that occur on the Salesforce object.

  1. If you want the trigger to fire before the insertion of record, you can use the “before insert” trigger event.
  2. If you want the trigger to fire after the insertion of record, you can use the “after insert” trigger event.
  3. If you want the trigger to fire before update of record, you can use the “before update” trigger event.
  4. If you want the trigger to fire after the update of record, you can use the “after update” trigger event.
  5. If you want the trigger to fire before the deletion of record, you can use the “before delete” trigger event.
  6. If you want the trigger to fire after the deletion of record, you can use the “after delete” trigger event.

One more trigger event that can be fired after undeletion is “after undelete”.

Trigger Types

Basically, there are two types of triggers: the “before” trigger and the “after” trigger.

  1. Before Trigger – It fires when a record is inserted, updated, or deleted. We use this trigger to validate or update the records before saving it into the database (Salesforce object) if we want to set the “Account Industry” to “Banking” if “Account Rating” is not NULL.
  1. After Trigger – It fires when another record is updated/deleted based on the existing record if we want to create a new “Contact” after the “Account” is created or updated from it.

Trigger Context Variables

It is important to see which trigger scenario is fired. We need to track on which trigger context does the trigger is fired. All trigger context variables return true if the trigger is fired because of that event. Let’s look at them one by one.

1. isInsert: If the trigger is fired due to an insert DML event, isInsert becomes true.

Example: Creating contact when “Account” is created.

2. isUpdate: If the trigger is fired due to an update DML event, isUpdate becomes true.

Example: If the “Account Name” is not NULL, populate the “Annual Revenue”.

3. isDelete: If the trigger is fired due to a delete DML event, isDelete becomes true.

Example: The account records are unable to delete if “Account Rating” is “Hot”.

4. isUndelete: If the trigger is fired due to an undeleted DML event, isUndelete becomes true.

Example: The account records are retrieved from the Salesforce recycle bin.

Trigger Syntax:

We can create an Apex script that fires based on DML instances using the “trigger” keyword followed by the trigger name. It asks on which Salesforce object does the trigger should happen during the creation of the Apex script itself. All the trigger events are specified after the Salesforce object.

trigger Trigger_Name on Salesforce_object_API (trigger_events) {

  statements...

}

Environment Setup

1. Go to the “Developer Console” and go to the “Select New” file. Then, choose “Apex Trigger”.

2. It asks the script name and Salesforce object such that the trigger is fired on this object. Click on “Submit” to create a new Apex trigger.

Scenario 1: Before Insert

When the account is created with “Education” industry, we fire a trigger that assigns the “Type” field to “Technology Partner” [Object – Account].

trigger Before_insert on Account (before insert) {

 

    for(Account account_iter : Trigger.New) {
       
        // Check if the Industry is 'Education'
        if(account_iter.Industry == 'Education'){
           
        // Set the Type to 'Technology  Partner'
         account_iter.Type = 'Technology  Partner';
        }
    }

}

“First, we iterate the account records and check if the industry is “Education” or not. If it is “Education”, we assign the “Technology Partner” to the “Type” field.

Test Case:

Go to the “Accounts” tab from the App Launcher and create an account with industry as “Education”. Check if the “Type” field is populated with “Technology Partner” or not.

Upon clicking on “Save”, you can see that “Type” is created with “Technology Partner”.

Scenario 2: After Insert and After Update

When the account is created with the “Warm” rating, we fire a trigger that creates a contact with “Contact LastName” as “Linuxhint-Account”, “Title” as “Manager”, and “Department” as “Sales” [Object – Account].

trigger After_insert_trigger on Account (after insert, after update) {
       
        List<Contact> contact_List = new List<Contact>();
       
        //Iterate through Account records
        for(Account account_obj : Trigger.new) {
           
            if(account_obj.Rating == 'Warm'){
               
           
            // Create new Contact object
            Contact cont_obj = new Contact();
           
            // Assign the values to three fields
            cont_obj.LastName='Linuxhint-Account';
            cont_obj.Title='Manager';
            cont_obj.Department='Sales';
           
            // Add these three fields to the list
            contact_List.add(cont_obj);
        }
       
        // Insert into the Contact object
        insert contact_List;
        }
   
    }

First, we create a list of “Contact” type and iterate the “Account” object. Inside the “for” loop, we check if the “Account Rating” is “Warm” or not. If it is “Warm”, we create “Contact” and assign three fields with the values and add this object to the contact list (declared previously). Finally, we insert these three fields into the “Contact” object using the insert DML.

Test Case:

Go to the “Accounts” tab from the App Launcher and create an account with the “Rating” as “Warm”. Check if the contact record is created with three specified fields.

Upon clicking on “Save”, you can see that “Contact” is created with three fields. Go to the “Contacts” tab.

We can see that three fields are created. Go to the “Details” tab to view the fields.

Scenario 3: Before Update

When the campaign is updated with “Conference” type, we fire a trigger that updates the “Status” field to “Completed” [Object – Campaign].

trigger Before_update_trigger on Campaign (before update) {

 

    for(Campaign campaign_iter : Trigger.New) {
       
        // Check if the Type is 'Conference'
        if(campaign_iter.Type == 'Conference'){
           
        // Update the Status to 'Completed'
         campaign_iter.Status = 'Completed';
        }
    }

}

First, we iterate the campaign records and check if the “Type” is “Conference” or not. If it is “Conference”, we update the “Status” field to “Completed”.

Test Case:

Go to the “Campaigns” tab from the App Launcher and open any existing record.

This record is of “Webinar” type and its status is “Planned”. Now, edit this record by updating the type to “Conference”.

We can see that the “Status” is updated to “Completed’.

Scenario 4: Delete (Before)

When we try to delete the records of the campaign object when the status is “Completed” or the type is “Conference”, we throw an error such that we will not be able to delete the records.  We display the error using the addError() method [Object – Campaign].

trigger delete_trigger on Campaign (before delete) {

 

    for(Campaign camp_iter : Trigger.old) {
       
        // Check if the Status == 'Completed' or Type == 'Conference'
        if(camp_iter.Status == 'Completed' || camp_iter.Type == 'Conference' ){
           
        // Specify the Error message.
          camp_iter.addError(' You cant delete this record if the Status == Completed or Type == Conference.');
        }
    }

}

Test Case:

Go to the “Campaigns” tab from the App Launcher and open any existing record with the “Completed” status or with the “Conference” type.

Click on “Delete” on the dropdown on the right.

We can see that error is thrown and it is not deleted.

Conclusion

Trigger is an Apex script that fires before or after the data manipulation instances. Based on the event that is specified in the trigger, it fires on specified objects in Salesforce. We learned the four different scenarios to fire the trigger upon insertion, update, and deletion with different examples on different objects. Here, we utilized the account, contact, and campaign objects for demonstration. You can follow the same examples on your custom objects.

Share Button

Source: linuxhint.com

Leave a Reply