Apex Trigger's

How to use Apex Trigger in salesforce 



Hello Friends,

In this blog, we are going to learn about how to use the apex trigger, for example in which condition we should consider for developing triggers on a standard/custom object in salesforce.

E.g.: As we can think about a condition like we have to calculate the total number of a contact on the account then we can not do this with Process builder and Work-Flow field update. In this condition, the Apex Trigger serves best our purpose.

We have the following event in trigger

  1. Before Event 
  2. After Event

We can develop the apex trigger below events:

  1. Before Insert (trigger.new)
  2. After Insert (trigger.new)
  3. Before update (trigger.new, trigger.old)
  4. After update (trigger.new, trigger.old)
  5. After undelete (trigger.new)
  6. After Delete (trigger.old)
To better understand the concept of apex trigger let assume a scenario where we want that Account Shipping Address should be the same as Account Billing Address if Billing Address is not equal to Shipping Address.

For this first, we have to create an Apex trigger 
  1. Click on Gear Icon,
  2. Here you see the Developer Console Option (If you are not able to see the Console Option Please contact your salesforce administrator)
  3. Now open Developer Console and click on New and Select-Object as Account and give the name as AccountTrigger click save.
  4. Now click on New again on Apex class and enter the name as AccountTriggerHandler and click save.
  5. Now copy the below code and paste on AccountTrigger and save:

    trigger AccountTrigger on Account (before insert){
        if(trigger.isBefore && Trigger.isInsert)
        {
                AccountTriggerHandler.CreateAccounts(Trigger.New);
        }   
    }


  6. Now copy the handler code and paste it in the AccountTriggerHandler and save:

    public class AccountTriggerHandler {
        public static void CreateAccounts(List<Account> acclist)
        {
            for(Account acc:acclist)
            {
                if(acc.ShippingState!=acc.BillingState)
                {
                    acc.ShippingState = acc.BillingState;
                }
            }
        }
    }

Your apex trigger and apex class which is trigger handler will look like the below images




This trigger will work only when a new Account is created because we have only one event in the trigger as before insert.

Whenever you create a new account with a Shipping address and Billing Address is blank or not equal to Shipping Address. This trigger will update the Billing Address as Shipping Address.

For more information you can watch the video from the below-mentiond link:




If you like the Content Please share it with your friends and if you have any Questions please Comment below.


Thanks 

Force Galaxy



Comments

Post a Comment