Saturday 14 May 2011

Writing Apex Trigger : My First Trigger

Hi,

Before we write our first trigger let us discuss the basix syntax of a trigger and what are the database activities/events which fires a trigger.
Syntax :

trigger <name> on Account (<events>) {

}
Here
1. Name is the name of the trigger this is required to provide and has to be unique for the object on which trigger is written. By uniqueness I mean to say that no two triggers on the same object can have similar name.

2. Events are the database activities which fires a trigger, this again is required for a trigger. So by this we can say Trigger is Apex Code that gets executed before and after of these operations.

  • Insert : Before and After
  • Update : Before and After
  • Delete : Before and After
  • Merge : Not directly, but both insert and delete trigger get fired for winning and losing records.
  • Upsert : Not directly, but both insert and update trigger gets fired
  • Undelete : After


Requirement : Now lets take an example of a requirement that whenever an Account gets updated then Fax field of the account should be copied in the fax field of all the contacts those have reference of this account.

trigger testReqTrigger on Account (after update) {
    for(Account acc : Trigger.New){
    List<Contact> listCon = [Select Fax from Contact where AccountId =: acc.id];        for(Contact con : listCon){
        con.Fax = acc.Fax;
        }
    update listCon;

    }

}
In above example we have not written the trigger which will use resources in optimized way, we will discuss trigger optimization in detail later.

Regards

No comments:

Post a Comment

Tweet