Apex can be invoked through the use of
triggers. A
trigger is
Apex code that executes before or after the following types of operations:
- insert
- update
- delete
- merge
- upsert
- undelete
For example, you can have a trigger run before an object's records
are inserted into the database, after records have been deleted, or
even after a record is restored from the Recycle Bin.
You can define triggers for any top-level standard object,
such as a Contact or an Account, but not for standard child objects,
such as a ContactRole.
Triggers can be divided into two types:
- Before triggers can be used to update or validate
record values before they are saved to the database.
- After triggers can be used to access field values
that are set by the database (such as a record's Id or lastUpdated field), and to affect changes in other records,
such as logging into an audit table or firing asynchronous events
with a queue.
Triggers can also modify other records of the same type as the
records that initially fired the trigger. For example,
if a trigger fires after an update of contact A, the trigger can also modify contacts B, C, and D. Because triggers can
cause other records to change, and because these changes can, in turn,
fire more triggers, the Apex runtime engine considers all such operations a single unit of work
and sets limits on the number of operations that can be performed
to prevent infinite recursion. See Understanding Execution Governors and
Limits.
Additionally, if you update or delete a record in its before trigger,
or delete a record in its after trigger, you will receive a runtime
error. This includes both direct and indirect operations. For example, if you update account A, and the
before update trigger of account A inserts contact B, and the after insert trigger of contact B queries for account A and updates it using the
DML update statement or database
method, then you are indirectly updating account A in its before trigger, and you will receive a runtime error.
Implementation Considerations
Before
creating triggers, consider the following:
- upsert triggers fire
both before and after insert or before and after update triggers as appropriate.
- merge triggers
fire both before and after delete triggers for the losing records and before update triggers for the winning record only. See Triggers and Merge Statements.
- Triggers that execute after a record has been undeleted only work
with specific objects. See Triggers and Recovered Records.
- Field history is not recorded until the end of a trigger. If you
query field history in a trigger, you will not see any history for
the current transaction.
- Do not write triggers that make assumptions about API batches. Salesforce may break up API batches
into sets smaller than those specified.