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!

Feature Flags in Lightning Web Components Have Never Been Easier

Salesforce continues to provide more and more features with direct access from the component level without developing in Apex. One of the more recent features made available directly to Lightning Web Components are Custom Permissions.

What Are Custom Permission?

Salesforce Custom Permissions are designed to provide a flexible, customizable approach to control access within an application. They allow administrators to define access rights at a granular level and developers to reference them in code. Here’s a brief breakdown of what Salesforce Custom Permissions are and what they should be used for:

Use Cases

Feature Access Control: They can be utilized to control who has access to certain features within an application. For example, access to specific buttons, sections, or any custom functionality can be controlled using custom permissions.

Custom Code Authorization: Developers can reference Custom Permissions in Apex code or Visualforce pages to control who can execute specific code paths. This enables a level of dynamic access control within custom code.

Component Visibility: Custom permissions can be used to control the visibility of certain components on a page based on the user’s permissions.

Advantages

Flexibility: They offer a high degree of flexibility in controlling access to custom functionality.

Maintainability: By encapsulating access control logic in a centralized manner, they can make the application easier to maintain and modify over time.

Creation and Assignment

Creating Custom Permissions involves defining a name and a label for the permission. Once created, these permissions can be assigned to users via Permission Sets or Profiles.

The assignment of Custom Permissions is quite flexible. They can be granted to users, groups, permission sets, or even entire profiles, allowing for a broad or narrow scope of access control based on the need.

Feature Implementation

Below is an direct example from Salesforce Documentation, referencing a Custom Permission from a Lightning Web Component, except with some more consistency.

hasPermission.js
-----------------
import hasPermission from "@salesforce/customPermission/PermissionName";
import hasPermissionManaged from "@salesforce/customPermission/namespace__PermissionName"; 

hasPermission references a Custom Permission that is unmanaged, while hasPermissionManaged is how you would reference a Custom Permission with a namespace.

hasPermission.js
-----------------
export default class App extends LightingElement {
    get isDisabled() {
        return hasPermission;
    }
}

hasPermission.html
-----------------
<template>
  <setup-panel-group>
    <setup-button disabled={isDisabled} onclick={openSetup}></setup-button>
  </setup-panel-group>
</template>

As you can see, they’ve made using the value of a Custom Permission very easy, creating a GET’r to use for an inline visibility flag.

See the Creating and Assignment header for examples how to relate the permission to various entities for access.