Search This Blog

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