What is apex trigger
An apex trigger is a piece of code in Salesforce that runs automatically when certain database events happen. These events include Insert, Update,Delete, or Undelete actions on records.
Apex triggers are helpful for automating business processes when these database events occur. They allow developers to customize salesforce so that business requirements are executed automatically based on changes to records or fields.
Apex trigger use case
A real-world example of trigger automation is when you make a purchase from an e-commerce website, a set of actions takes place for the delivery of the goods.
- The payment is marked as completed.
- The stock is updated, and an order is created for the customer.
- The merchant receives a notification for the item sold.
- The shipping department receives a notification for the upcoming delivery.
Payment Finalised
The payment is successfully processed.
Stock Update
The system updates the stock quantity.
Merchant Alert
The merchant receives an order notification.
Shipping Alert
The shipping department gets a notification for the delivery.
Types of apex triggers
Triggers can be set to run either before or after a record is created, updated, deleted, or undeleted:
Before Triggers
Before triggers allow you to validate or modify data before a record is saved. Before triggers are used to perform data validation and field updates on the records before saving them to the database.
After Triggers
After triggers are used when you need to perform actions with data that’s already saved, like updating related records or calculating complex values. After triggers are used to perform record updates on separate record/object once data is saved into the database.