Here's a cheat sheet for Apex triggers with code examples:
1. Trigger Structure:
trigger TriggerName on ObjectName (trigger_events) {
// Trigger logic and code here
}
2. Trigger Events:
- before insert: Fires before records are inserted into the database.
- before update: Fires before records are updated in the database.
- before delete: Fires before records are deleted from the database.
- after insert: Fires after records are inserted into the database.
- after update: Fires after records are updated in the database.
- after delete: Fires after records are deleted from the database.
3. Trigger Context Variables:
- Trigger.new: Returns the new versions of the sObject records.
- Trigger.old: Returns the old versions of the sObject records.
- Trigger.newMap: Returns a map of IDs to the new versions of the sObject records.
- Trigger.oldMap: Returns a map of IDs to the old versions of the sObject records.
4. Trigger Example:
trigger AccountTrigger on Account (before insert, after update) {
if (Trigger.isBefore) {
if (Trigger.isInsert) {
// Trigger logic before insert
}
} else if (Trigger.isAfter) {
if (Trigger.isUpdate) {
// Trigger logic after update
}
}
}
5. Handling Trigger Events:
// Before Insert Trigger
trigger ContactTrigger on Contact (before insert) {
for (Contact contact : Trigger.new) {
// Perform logic on each new contact before insert
}
}
// After Update Trigger
trigger CaseTrigger on Case (after update) {
List<Case> updatedCases = new List<Case>();
for (Case c : Trigger.new) {
Case oldCase = Trigger.oldMap.get(c.Id);
if (c.Status != oldCase.Status) {
updatedCases.add(c);
}
}
// Perform logic on updated cases after update
}
Remember to replace TriggerName with the name of your trigger and ObjectName with the name of the object (e.g., Account, Contact, Case) you're working with.
This cheat sheet provides a basic structure and examples to get you started with Apex triggers. Keep in mind that you might need to add additional logic based on your specific requirements.