Creating Simple Apex Trigger

Apex Trigger could be described as an action that is triggered by a particular event. In salesforce, the trigger is the apex program or the code which gets executed before or after certain types of operations. These operations are described below.

  • Insert
  • Update
  • Delete
  • Undelete

Triggers will be executed before the object records are inserted, updated, or deleted into the database or after records are inserted, updated, deleted, and restored.

There are two types of Apex Trigger, as described below.

  • The first one is those that are saved to the database before triggers can be used to update or validate record values before.
  • The second variant is the after triggers, these after triggers can be used to access field values that are set by the database, and to affect changes in other records.

Creating a trigger

Triggers can be created by a simple syntax as shown below.

trigger <TriggerName> on ObjectName (<events>) {
    // we can write our code here.
}

Let us cite an example, do see how the trigger works. In this example, when an account is inserted, automatically contact will be created for that account. This will demonstrate how a trigger works in a real-time scenario. The mentioned example will be accomplished with the help of the code given below.

trigger insertContact on Account (after insert) {
   Contact cont = new Contact();
   cont.LastName = Trigger.new[0].name;
   cont.AccountId = Trigger.new[0].ID;
   insert cont;
}

This code demonstrates, how a simple trigger can be used to insert contact when an account is created.

Trigger Variables

For run time context, we can have different variables for the trigger.

  • Trigger.New :- This context variable returns a list of new records of the sobjects which needs to be inserted into the database.
  • Trigger.old:- Trigger.old returns a list of old records of the Sobjects from the database.
  • Trigger.NewMap:- Trigger newMap returns a map of IDs to the new records of the Sobjects.
  • Trigger.OldMap:- Trigger.OldMap returns a map of ids to the old records of the SObjects.
  • Trigger.isAfter:- Trigger.isAfter returns true if this trigger was fired after all the records we saved.
  • Trigger.isBefore:- This variable returns true if the trigger was fired before any record was saved.
  • Trigger.is Insert:- This context variable returns true if the trigger was fired due to an insert operation.
  • Trigger .is Update:- This context variable returns true if the trigger was fired due to an update operation.
  • Trigger.isDelete’:- This context variable returns true if the trigger was fired due to a delete operation.
  • TriggerisUndelete:- This context variable returns true if the trigger was fired after a record is recovered from the recycle bin.