Wednesday, July 2, 2014

Change your trigger on the fly using Custom Settings



Preface: this post is part of the Advanced Apex Concepts series.
Custom Settings are a hidden gem in Apex that always impresses people, especially bosses!
Custom Settings are variables that you use in your code but set and modify outside of your code.
Here’s an example:
You’re writing a trigger that sets a “Customer Service Rep” field on an Account every time there’s a high value Opportunity associated with it. Two things are certain: (1) The CSR on duty changes every week and (2) the threshold for a “high value” opp changes often since your company is expanding.
A perfect use case to use Custom Settings to set the CSR on duty and the “high value” opp threshold!
Benefits of using Custom Settings:
  • Change your variables through Salesforce.com without deploying code!
  • Any non-coder admin can now modify your variables and change how your code works!
  • Show your boss that you’re thinking ahead and not just concerned with doing the bare minimum!
Step 1: Create a Custom Setting “object” for your trigger:
Setup >> Develop >> Custom Settings >> New

Step 2: In your Custom Setting object, create Custom Fields for each needed variable:

Step 3: Create a Custom Setting record and edit its variables
Navigate to your Custom Setting >> Manage >> New

Step 4: Use your Custom Setting in your code!
trigger AddCSR on Opportunity (before insert) {
// Grab your Custom Setting values CSR_Settings__c settings = CSR_Settings__c.getInstance('csr'); String CSR_USER_ID = settings.CSR_User_ID__c; Decimal OPP_MIN_VALUE = settings.Opp_Minimum_Value__c;
// Create a master list of accounts to bulk update List<Account> accounts = new List<Account>(); for (Opportunity opp : Trigger.new) { // Make sure we meet the minimum threshold
if (opp.Amount >= OPP_MIN_VALUE) {
// This is a trick to get the related account! Account acc = new Account(); acc.Id = opp.AccountId; // Update the CSR and add to master list
acc.CSR__c = CSR_USER_ID;
accounts.add(acc); } } // Update the master list of accounts update accounts; }
Now if you need to edit the CSR on duty or the minimum Opportunity amount threshold, simply edit the record in Step 3 – no rewriting or deploying code necessary!
One important note – custom Settings aren’t automatically transferred between sandboxes and production, so make sure you include them in both places or your code will break!

2 comments: