Skip to main content

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 SampleTrigger on Opportunity (after insert) {
Opportunity TheOpportunity =[0];
Account theAccount= [Select Type, Amount, name from Account where id:=theOpportunity.Accountid];
update theAccount;

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.


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 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, 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[0], if the record is updated using a data loader, we need to loop through 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 =[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:

Account theAccount= [Select Type, Amount, name from Account where id:=theOpportunity.Accountid];
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 blog.

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


Popular posts from this blog

The curious case of the custom redirection on Salesforce Console

Every developer worth their salt knows that the easiest way of redirection from a page to another is by using everyone's favorite function

public PageReference redirect() { PageReference pageRef = page.peskyProblemRedirection; pageRef.setRedirect(true); return pageRef; }
And the method is called by adding it to the Action attribute of the CommandButton or link, which works like charm and the user is redirected to the page after completion of the action.
So why am I going back to the basics? Because this way of redirection causes a pesky little problem in using the Service Cloud or Sales Cloud console.

Let's illustrate the problem, let's say you have a visualforce page as follows:

<apex:page sidebar="false" showHeader="false" controller="myExampleController"> <apex:form > <apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton action="{!Redirect}&qu…

Some PDF tricks on Visualforce: Landscape, A4, page number and more

The beauty of Visualforce is simplicity. Remember the shock you received when you were told the entire page renders as PDF if you just add renderAs=PDF to the Page tag.

For those who thought I spoke alien language right now, here is the trick, to render a page as PDF, we add a simple attribute to the <apex: page> tag

<apex: page renderAs='pdf'> This will render the entire page as PDF.

Now, say we need to add some extra features to the PDF. Like a page number in the footer or we need to render the page in landscape mode. Faced with this problem, I put on my Indiana Jones hat and went hunting for it in the vast hay-sack of the internet (read: googled extensively). Imagine my happiness when i found a big big page with many big big examples to solve the problem. The document I am referring to is from W3C, paged Box media.

Long story short, I now possess the ultimate secret of rendering the page in any format I want. So here are few tricks I learned from the page. To p…

Cache me if you can: What you should know before daring to set URL parameter on visualforce

If someone gave me a pence for every time there was an SOQL query in an APEX Class without using Limit or a condition during a code review, I could afford a Lamborgini this month. Sigh. If only. We make it a habit of going digging for data, at the very moment we need it. The crux of this problem happens when you have chain classes which are independent of each other. Each class needs the reference from a single record and we have to query for that record every single time.

While we don't see it, every SOQL query has a cost to it, and it does not go in my Lamborghini fund, however, it should. In a recent project, we had to construct an Account 360 page that could fetch information from different integration points. The page was also called using a live telephony integration, which could pass the phone number for the account. This required an ability to keep in context the Account that was on call.

Passing the Account id in URL parameter was a valid option, however, any manipulatio…