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,
trigger SetBuyingTimeFrame on Opportunity (before update) { for(Opportunity opp : Trigger.New) { opp.Buying_Time_Frame__c = '1-Immediate'; } } |
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'; } } } |
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';} } } } |