How to write a simple apex trigger in salesforce


I have started writing on salesforce tutorials and written down some tutorials on it as part of tutorial in today post i am going to tell you how to write a simple apex trigger in salesforce , to write my trigger i will use eclipse IDE but you can use any other way look at my post on how to write codes in salesforce , so before starting how to write a apex trigger it is important to talk about trigger.

What is an Apex Trigger ?

Trigger is piece of code which execute on a particular events like on insertion , deletion (there are more events) of records so there can be two type of scenario on which trigger would work and it would be after insertion or before insertion.Trigger work in two cases before any event and after that event.Now lets see how many events are there on which trigger work.

  • Insert
  • Update
  • Delete
  • Undelete

As i already told you that trigger will work on two cases after and before of a particular event so the total cases would become .

  • After Insert
  • Before Insert
  • After Update
  • Before Update
  • Before Delete
  • After Delete
  • After Undelete

There is no such ‘Before Undelete’ event because there can never be any scenario where you need to execute a trigger before undeleting a record

When to use Before and After in Apex Trigger

Before Trigger :
Before trigger are used to access the data which are going to be filled in the records so it can use for the validation purposes before saving the data in the database.

After Trigger :
After trigger are used to access the data which are available after saving the records so it can also use to have the access the id of the record that are saved recently.

A simple Example of trigger

I will use eclipse to write code , it would create general syntax for trigger , but for those who don’t the syntax please take a look at the below code .

trigger <TriggerName> on ObjectName (<events>) {

// you can write your code here.


Now let say i have an object in my salesforce ‘position’ and i want to validate that a particular field ‘Hello’ should either have ‘test’ as a value in the field or if ‘test’ is not the value then ‘yahoo’ should enter the field

trigger ValidateHello on Position__c (before insert) {

List<Position__c> positions =;   // use to access all the values of the fields for (Position__c p:positions){   //for each loop if (p.Hello__c != ‘test’) { p.hello__C=’yaho0′; } } }

So this is a simple trigger example i hope you like my this post if you have any query you can leave your comments in the below section i would love to answer them and don’t forget to subscribe to my blog and like my Facebook page.

Related Articles :

Speak Your Mind



This site uses Akismet to reduce spam. Learn how your comment data is processed.