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
- Before Event
- After Event
We can develop the apex trigger below events:
- Before Insert (trigger.new)
- After Insert (trigger.new)
- Before update (trigger.new, trigger.old)
- After update (trigger.new, trigger.old)
- After undelete (trigger.new)
- 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
- Click on Gear Icon,
- Here you see the Developer Console Option (If you are not able to see the Console Option Please contact your salesforce administrator)
- Now open Developer Console and click on New and Select-Object as Account and give the name as AccountTrigger click save.
- Now click on New again on Apex class and enter the name as AccountTriggerHandler and click save.
- 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);
}
} - 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
This comment has been removed by the author.
ReplyDeleteINSIGHTFUL POST
ReplyDelete