Wednesday 31 March 2021

Apex Triggers in Salesforce

 Hello All, 

Before we write any example let us first understand what are Triggers.

Just like database triggers that execute on/after/before certain event to execute a set of statements, Apex triggers also server the same purpose.

Triggers allows us to do custom actions on events, i.e. do some field setting, fire SOQL statement, execute some complex equation,

supported events ,

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

sample Trigger syntax,

trigger TriggerName on ObjectName (trigger_events) {                  

//code here 

}


TriggerName is unique Name for Trigger, Object Name is Entity Name,

Note : in the below example we are using Context to get the current record details,
for(Opportunity opp : Trigger.New)

e.g.

1. set a Field value when a Opportunity record is updated

trigger SetBuyingTimeFrame on Opportunity (before update) {
for(Opportunity opp : Trigger.New)
{
opp.Buying_Time_Frame__c = '1-Immediate';
}
}

2. Using a If Else condition in trigger

trigger SetBuyingTimeFrame on Opportunity (before update) {
for(Opportunity opp : Trigger.New)
{
if(opp.Enquiry_Classification__c=='1-Excellent')
{
opp.Buying_Time_Frame__c = '1-Immediate';
}
else 
{
opp.Buying_Time_Frame__c = '5-Within 3 Months';
}
}
}

2. Using a switch statement in trigger

ttrigger SetBuyingTimeFrame on Opportunity (before update) {
for(Opportunity opp : Trigger.New)
{
switch on opp.Enquiry_Classification__c{
when '1-Excellent' {opp.Buying_Time_Frame__c = '1-Immediate';}
when '2-Very High' {opp.Buying_Time_Frame__c = '2-Within 1 Week';}
when '3-High' {opp.Buying_Time_Frame__c = '3-Within 2 Weeks';}
when else {opp.Buying_Time_Frame__c = '5-Within 3 Months';}
}
}
}

the examples are endless :-), more details are available on link, 

No comments:

Post a Comment

Siebel GoTo View - Handling Realtime cases

 Hello All,  We all must have used GoTo view functionality of siebel to navigate to a particular view from current view. What if the require...