This course is currently a work in progress. Please join the waitlist to receive regular updates.

Before triggers in apex

The before triggers are used for handling field updates and validations on records before saving them to the database in order to auto-calculate field values and reduce the manual effort required to fill them.

They can also be used to perform validations based on the record values, ensuring that users don’t make mistakes when saving records and keeping them as accurate.

An example of a trigger scenario validate a candidate's years of experience when processing a job application. For example, if the job requires five years of experience and the candidate has only three years, the system will mark the candidate as not qualified.

Here are few scenarions where to use before triggers in salesforce:

1. Setting Default Values

You can set default values for fields based on certain conditions. For instance, if the company name is empty on a lead record, prepopulate it with "To be advised."

2. Field Modification

If you need to modify field values before saving a record, before triggers are the right choice. For example, if you want to populate the billing address with the same information as the shipping address on an account.

3. Data validation

Before triggers can validate data entered by users to ensure it meets your organization standards.

4. Preventing Duplicates

Before triggers can be used to check existing records in the database and prevent the creation of duplicate records. For example, you prevent adding a duplicate contact to an account by using the email address.

5. Creating a parent record

If you need to link a parent record every time a child is created you can implement them in before trigger. For example, if you want to create an account record whenever a contact is created, you can Insert account in the contact's before trigger.

Apex Trigger Order of Execution

Loads the original record from the database or initializes the record for insert.

Loads the new record field values from the request and overwrites the old values.

Executes all before triggers.