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:

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.

Comments

  1. This is super helpful....I would say pretty clean and simple....well done...

    ReplyDelete
  2. awesome man..........i am new to SFDC.Your explanation is so understandable:)

    ReplyDelete
  3. Hello,

    First of all thankyou for supporting the SFDC community. I have two questions (may be stupid) but i am quite new to SF.

    Question 1.

    Opportunity TheOpportunity = trigger.new[0];

    after every object you prefix the (is it something standard?) for ex above you have mentioned 'Opportunity TheOpportunity' it seems to be a variable/alias name but do we need to prefix the always?

    Q2. why have you pulled type and amount in the select query below if you only need name for the account?

    Account theAccount= [Select Type, Amount, name from Account where id:=theOpportunity.Accountid];

    can you please shed some light?

    ReplyDelete
    Replies
    1. Hi Ish,
      Thank you for the comment. Well I dont think any question is a stupid question. So let me answer your questions.
      Q1. The 'The' notation format is Salesforce standard. If you open the source code (Ctrl+u on Chrome) you will see that is how Salesforce gives the IDs to the objects. I am working on Salesforce since the days of S-Control (outdated technology before visualforce) where we used to view source a lot and replicate the thing using JS. The habit is quite stuck. :)

      Q2. Good point, that should be a lesson to me. I should keep a note. We do not need the other fields, I was thinking of something else before. It happens. Thanks for pointing out.

      Delete
  4. for begginers,this explnation is very much helpful......

    ReplyDelete
  5. When I ran this in force.com I got an error due to the semi colon in id:=theOpportunity.Accountid]. Any ideas?

    ReplyDelete
    Replies
    1. Make sure you copy-paste this in a notepad first. On HTML pages formating ruins most things.

      Delete
    2. It should be id=:theOpportunity.Accountid]. Colon (:) would come after equal sign (=).

      Delete
  6. It is very useful for beginners to write the code

    ReplyDelete
  7. THANK YOU!

    As a youn SF administrator, this has helped me SO much.

    Cheers buddy!!

    ReplyDelete
    Replies
    1. :D You are welcome... that was intention of this trigger.

      Delete
    2. Hi Iam in learning stageof SFDC this is very helpful to us,we need ur suggestions on SFDC

      Delete
  8. 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)

    is it from Trigger.Old[0] or Trigger.new[0]?

    ReplyDelete
    Replies
    1. It is from trigger.new[0] the only reason why you will need trigger.old would be probably to save the values in Update trigger.

      Delete
  9. I want to delete only those accounts with whom any opportunities are associated.that means accounts without any opportunities only get delete..how would i write trigger for that?

    ReplyDelete
  10. Can you suggest how to write a trigger on a selection of a lookup custom recird to populate a currency field? Thanks in advance.

    ReplyDelete

Post a Comment

Popular posts from this blog

Video: Top ten tips on how not to ruin Salesforce implementation

Another presentation for the London Salesforce Developer Group using mobile app. 
When it comes to Salesforce development, we all know what it takes to deliver stuff. Having a certified professional helps you gain a knowledgeable partner but what about the things such as common sense?  We all know how to deliver things on client requirements but what about things that are not mentioned by the client. We will be discussing in details things that will enhance the user experience, focus on tips to read your customers mind and have a bit of perspective on the user experience.

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…

Four secrets to improve the usability of your visualforce/Lightning pages on Salesforce

In the immortal words of a certain machine returning back in time, I am back. For now. After procrastinating for over a year and drafting a lot of rants- I am back with a very important coding lesson for you. For now.

When we are designing a Visualforce page or an app or a lightning component (added that only to trick google) or any web page for that matter, we often tend to wrap up things quickly. Ask anyone on the team, how to design a good User Experience? and the person will immediately throw buzz words like Bootstrap, angular and other useless libraries (did someone squint?)

Ok, Bootstrap, Angular-Js, and all the libraries are really cool and are useful in designing a fabulous UI. They are helpful in creating responsive pages that will work on all the devices but this post is not about those. Nope. For the purpose of this post, all the external libraries and buzzwords you use to decorate your resume are useless. (Adding Angular JS in your resume for a Salesforce consultant posit…