3.3 Considerations of writing triggers and some best practice

Before we proceed to the next example, there are a few concepts and considerations we need to go through for the triggers.

Bulk trigger

In Apex, every trigger is a bulk trigger. Which means there can be up to 200 elements in trigger.new list. Always keep that in mind and always think about bulkification when you write your trigger code.

Trigger context variables

We have a bunch of trigger context variables for us to use. Trigger.new is just an example of them.

The most frequent used ones can be categorised into three groups:

  1. Trigger.New, Trigger.Old, Trigger.NewMap, Trigger.OldMap. Those four context variables are containers of the SObject records. New means the records with updated value. Old means previous records with previous values. Map means an Map<Id, SObject> map from the SObject Id to the record itself.
  2. Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete. Those four boolean variables tells whether the current trigger is an insert/update/delete/undelete trigger.
  3. Trigger.isBefore, Trigger.isAfter. Tells whether it is a before trigger or after trigger.

Context variable considerations

The full list of considerations are here.

What you especially need to pay attention to is:

  1. You can’t directly do DML to Trigger.New.
  2. Trigger.Old is always read only
  3. Trigger.New is readonly in after trigger.

One trigger for each SObject

You can have multiple triggers for one SObject. But it is never recommended. The execution sequence of those triggers are random so it will be disastrous.

Next Post

3.4 Write a more difficult trigger

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

#Apex#Tutorial

Leave a Reply

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