Salesforce Apex Triggers: Snippets & Helpful References

Hey there, Salesforce savants! 🌟 Are you ready to jazz up your Salesforce game with some snazzy Apex Triggers? You’re in for a treat! Today, we’re diving deep into the world of Salesforce Apex Triggers, armed with not just code examples but also a dash of charm and a sprinkle of humor. Let’s get our coding groove on!

There are many ways to develop Apex Triggers, but there are definitely better ways than others. Here are some examples of ways leading to a happy path.

The Art of Trigger Frameworks: Choose Your Weapon

Before we jump into the code, let’s talk frameworks. Yes, frameworks! They’re like the secret sauce that makes your triggers oh-so-tasty and maintainable.

Kevin O’Hara’s SFDC Trigger Framework

  • Pros: Perfect for beginners! It’s like the friendly neighborhood of Apex Triggers, welcoming and easy to get around. This is actually my favorite and go to framework.
  • Cons: A bit like that finicky old car – you have to handle exceptions carefully, and there’s some annoying casting.

Link: https://github.com/kevinohara80/sfdc-trigger-framework

Trigger Handler Pattern

  • Pros: It’s like having a tidy kitchen; everything’s where you need it. This pattern keeps your triggers well-organized and easy to test. Think of it as the Marie Kondo of Apex Triggers.
  • Cons: Watch out for the occasional clutter – there can be duplicated code in every trigger.

Link: https://www.apexhours.com/trigger-handler-pattern-in-salesforce/

Virtual Class Framework (TriggerHandlerBase)

  • Pros: This one’s the minimalist of the group. Easy to implement, and you only override what you need. It’s like having a Swiss Army knife but only pulling out the tools you need.
  • Cons: It’s simple, maybe too simple for the trigger gurus looking for more sophisticated solutions.

Link: https://metillium.com/2019/02/a-simple-trigger-framework/

Apex Trigger Showtime: Code Examples

Below is boiler plate Apex Trigger code for common automation use cases that can be edited to fit whatever framework you might be interested in implementing. Happy coding!

Account Validation Trigger

You want to make sure nobody’s messing up your account records with incomplete data, right? Let’s ensure all necessary fields are filled in.

trigger AccountValidationTrigger on Account (before insert, before update) {
    for(Account acc : Trigger.new){
        if(String.isBlank(acc.Phone) || String.isBlank(acc.Industry)){
            acc.addError('Hey! Don’t forget the Phone and Industry.');
        }
    }
}

Opportunity Rollup Summary

Imagine you’re a math whiz, summing up all those Opportunities’ Amounts on an Account. That’s what this trigger does, automagically!

trigger OpportunityRollupSummary on Opportunity (after insert, after update) {
    // Collect the IDs of the affected accounts
    Set<Id> accountIds = new Set<Id>();
    for (Opportunity opp : Trigger.new) {
        accountIds.add(opp.AccountId);
    }

    // Query the total Opportunity amounts for each account
    Map<Id, Decimal> accountOpportunitySum = new Map<Id, Decimal>();
    for (AggregateResult ar : [
        SELECT AccountId, SUM(Amount) totalAmount
        FROM Opportunity
        WHERE AccountId IN :accountIds AND IsClosed = false AND IsWon = true
        GROUP BY AccountId
    ]) {
        accountOpportunitySum.put((Id)ar.get('AccountId'), (Decimal)ar.get('totalAmount'));
    }

    // Update the accounts with the new total Opportunity amounts
    List<Account> accountsToUpdate = new List<Account>();
    for (Id accountId : accountIds) {
        Account acc = new Account(Id = accountId, TotalOpportunityAmount__c = accountOpportunitySum.get(accountId));
        accountsToUpdate.add(acc);
    }

    if (!accountsToUpdate.isEmpty()) {
        update accountsToUpdate;
    }
}

Case Assignment Magic

Assigning Cases can feel like playing whack-a-mole. This trigger automates it so you can chill while the code does the heavy lifting.

trigger CaseAssignment on Case (before insert) {
    // Define your queue IDs here. In a real scenario, you would query
    // these or use Custom Settings/Metadata API for better
    // maintainability

    // Example Queue ID for Tech Support
    Id techSupportQueueId = '00GXXXXXXXXXXXXXXX';
    // Example Queue ID for Customer Service
    Id customerServiceQueueId = '00GXXXXXXXXXXXXXXX';

    // Loop through each case in the trigger
    for(Case c : Trigger.new) {
        // Assign to Tech Support Queue if the case is of type 'Technical'
        // and priority is 'High'
        if(c.Type == 'Technical' && c.Priority == 'High'){
            c.OwnerId = techSupportQueueId;
        }
        // Assign to Customer Service Queue if the case is of type
        // 'Customer Service' and priority is 'Medium'
        else if(c.Type == 'Customer Service' && c.Priority == 'Medium'){
            c.OwnerId = customerServiceQueueId;
        }
        // You can add more conditions here as per your business
        // requirements
    }
}

Trigger Best Practices: The Golden Rules

  • Bulkify Your Code: Always think in bulk! Salesforce is like a party – you want your triggers to handle a crowd, not just one guest.
  • Avoid Recursion: It’s like a hall of mirrors; you don’t want to get stuck! Use static variables to prevent triggers from calling themselves over and over.
  • Use Comments: Document your code like you’re writing a diary. Future you will thank you!

Wrapping Up With a Bow

And there you have it, folks – a whirlwind tour of Salesforce Apex Triggers! Remember, with great power comes great responsibility. Use these frameworks and examples wisely, and you’ll be the Trigger Titan of your Salesforce realm. Happy coding, and may your debug logs always be error-free!

Leave a Reply

Your email address will not be published. Required fields are marked *