Apex Trigger Guide — My First Post

Hey everyone, this is my first post here. I thought I’d start with something simple but super useful — Apex Triggers. If you're getting into Salesforce development, this is one of those things you'll see everywhere.

In simple terms, a trigger is just code that runs automatically when data changes. You create or update a record, and the trigger fires in the background. No button clicks, no manual steps.

Example Trigger


trigger AccountErrorTrigger on Account (before insert, before update) {
    for (Account acc : Trigger.new) {
        if (acc.Name != null && acc.Name.contains('ERROR')) {
            acc.addError('Name cannot contain ERROR');
        }
    }
}
  

What this does is pretty straightforward. Before saving an Account, it checks the name. If someone tries to use the word "ERROR" in the name, Salesforce blocks the save and shows a message.

For example, if a user tries to create something like Test ERROR Company, it simply won’t go through. This helps keep bad or unwanted data out of the system.

A small improvement

In real projects, I usually don’t keep all logic directly inside the trigger. Even for simple checks, it’s better to keep things cleaner and reusable.


trigger AccountValidationTrigger on Account (before insert, before update) {
    AccountValidationHandler.validateAccounts(Trigger.new);
}
  

public class AccountValidationHandler {
    public static void validateAccounts(List<Account> accounts) {
        for (Account acc : accounts) {
            if (acc.Name != null && acc.Name.toLowerCase().contains('error')) {
                acc.addError('Please avoid using restricted words like "ERROR" in the name.');
            }
        }
    }
}
  

Same logic, just structured in a cleaner way so it’s easier to extend later.

One thing to remember

Always assume multiple records, not just one. Even if you're testing with a single record, Salesforce can process data in bulk behind the scenes.

That’s why you’ll always see loops like for (Account acc : Trigger.new).

That’s it for this post. Keeping it simple for now. Next, I’ll probably cover when to use before vs after triggers and how things look in real projects.

← Back to Apex