Wednesday , August 23 2017
Home / Apex / Apex Programming for beginners / Apex Trigger / Writing a Simple Apex Trigger !!

Writing a Simple Apex Trigger !!

Writing a Simple Apex Trigger !!

 

Now we know where to write a Trigger, let’s begin with a simple example. In this scenario I would like to add a custom text in the last name of a contact.

Let’s have a look at the basic structure of a trigger

trigger MyCustomTriggerName on CustomObject__c (trigger_events) {

Line of codes to execute(Business Logic)

}

 

Using the above-mentioned structure we will write our code, in the above code we can give Trigger any name we want, and since we want the trigger to be on contact standard object, the structure of trigger looks like below

 

trigger ContactTestTrigger on contact (before insert) {

Line of codes to execute(Business Logic)

}

 

Now that we have defined the basic structure of the trigger now we will write the business logic as discussed in the beginning.

 

trigger ContactTestTrigger on contact (before insert) {

for(contact con : Trigger.new){

con.lastname  = ‘New Last Name using Trigger’;

}

}

Simple Apex Trigger

This is it, we have written a simple Trigger which initiates at before insert event of a contact. Based on the occurrence of the DML event, there are broadly two types of Triggers; Before Trigger and After Trigger. Further, the trigger can be classified into the below groups based on the events.

  1. Before insert, after insert.
  2. Before update, after update.
  3. Before delete, after delete.
  4. Before undelete.

 

In Trigger, we can modify the data without explicitly calling any DML operation, and if the operation is performed then it results in an error. The record is committed to the database once the trigger has completed its execution

 

Here you also see the use of a variable Trigger.new in the for loop, it is a trigger’s context variable.  Trigger’s context variable holds the values of the record which initiated the execution of the trigger, for e.g. Trigger.New contains the list of contacts which initiated the trigger. There are some Trigger’s context variables which return Boolean values and with the help of context variables, we can determine which event fired the trigger. There are many context variable available in Salesforce and can be studied in detail here.

This concludes how to write a Simple Trigger

Next, I would like to present, how to call apex class method in trigger, callout, and using trigger exceptions

About Sumit Datta

Leave a Reply

Your email address will not be published. Required fields are marked *