Friday, January 6, 2012

The Basics of writing a Apex Trigger

One of the most important and common asked question on Forums and everywhere is how do I write a trigger. Coding in Apex Trigger is like going to a dentist for a root canal, you keep dreading the moment until you realize it is actually not going to hurt you. If you plan to write an Apex Trigger this quick guide will help you doing so.

The first and foremost rule in writing a trigger is to remember the oldest suggestion given to the most comprehensive Hitchhikers Guide to Galaxy, 'Don't Panic.' Writing a trigger is not a rocket science, in-fact we should thank the team at Salesforce and ForceDotCom for making everything so simple, that anyone can do it.

Enough of talk, lets code.

So you want to write a trigger. Let us have a glimpse of what we are going to build. The problem statement is as follows

Problem: When the User is entering the Opportunity, check for the Opportunity Amount. If the Opportunity Amount is greater than 50,000. Mark the Parent Account as 'Featured'.
Solution: We will be modifying the parent Account Type field to 'Featured' and select value from Opportunity Amount.
Trigger:

trigger SampleTrigger on Opportunity (after insert) {
Opportunity TheOpportunity = trigger.new[0];
if(TheOpportunity.amount>50000){
Account theAccount= [Select Type, Amount, name from Account where id:=theOpportunity.Accountid];
theAccount.type='Featured';
update theAccount;
}
}

Explanation:
Let us look at the trigger one by one.


Step 1:

trigger SampleTrigger on Opportunity (after insert) {

Trigger Keyword suggest this is a trigger, the SampleTrigger is the name of the trigger. The trigger is written on the Opportunity Object. The Event that the code runs is written inside the bracket.
The following operations are possible in a trigger.

insert
update
delete
merge
upsert
undelete

There are two types of Triggers:
Before triggers are used to update or validate record values before they are saved to the database. A before insert trigger can change the value in the field. We won't get before undelete trigger.

After triggers can be used for a much more complex purposes, like updating a value of some other object when this is updated. Or it can also be used to trigger some other event (like workflow and approval process). The events that run behind the scenes are as follows:

So choose the object, choose the event and finally choose the type of trigger.
When we write a trigger, the Force.com server automatically sends us the value that was operated on in a variable called Trigger, this is called Context Variable.

Suppose I am updating the Opportunity named 'Opportunity1' on the opportunity edit page. In the before update opportunity trigger, Force.com will send all the values that were existing before the record was updated in the list called Trigger.Old and the new values that the user added in the list called Trigger.New.
 If there is a bulk updation using data loader, all the values will be in the above two list. It is logical to understand that we won't get Old values in a Insert event and we won't get new values in the Delete event (Cos they don't exist)

If the record is updated from the web browser, Salesforce application we will find always find the value in Trigger.new[0], if the record is updated using a data loader, we need to loop through Trigger.new one record at a time as shown in the figure below.


Now lets look at the line number 2 in the trigger above.
Step 2:
Opportunity TheOpportunity = trigger.new[0];

We just brought the first record updated from the Trigger.Old[0] to TheOpportunity variable (We can directly operate on Trigger.old[0] however code looks messy, developer is an endangered species, spare the messiness)

The next loop is straight forward.

The rest is easy:

if(TheOpportunity.amount>50000){
Account theAccount= [Select Type, Amount, name from Account where id:=theOpportunity.Accountid];
theAccount.type='Featured';
update theAccount;
}

We select the Amount field and check if it is greater than 50,000. If it is, we can fetch the parent Account on the Opportunity using the AccountId field. This post is not about the queries, but if you need help on understanding queries there is a beautiful article written on the Force.com blog.

Thats it then, remember the first rule in writing a trigger, 'Don't panic' rest all is easy.

Toodles.