[SalesForce] Using Custom Settings in Apex Trigger to Call Different Values for Sandbox/Production

I have an Apex Trigger for a Salesforce integration that looks like this in the Sandbox environment:

trigger Trigger_5074086a_493f_48d2_a8fd on Opportunity (after insert, after update, after delete, after undelete) {

    String url = 'https://test.dev.wi.com/api/hook/agh0UD9J0kio_Qd';
    String accessKey = '2c072ad68ac3039fca9fa868a3033f95ea165213136f';

    String content;

    if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
        content = wiWebHook.json(Trigger.newMap.keySet());
    } else {
        content = wiWebHook.json(Trigger.oldMap.keySet());
    }

    wiWebHook.callout(url, content, accessKey);
    }
}

The problem with this is that the string URL and Access Key are hard coded in the Trigger and they are only valid for my Dev Site. The String URL and Access Key is different for Production.

I have created a Custom Settings object called WILead__c with 2 fields which each contain the correct URL:

String_URL_Dev__c has a value of

https://test.dev.wi.com/api/hook/agh0UD9J0kio_Qd

String_URL_Live__c has a value of

https://test.production.wi.com/api/hook/agh0UD9J0kio_Qd

I have also created a Custom Settings object called WIAccessKey__c with 2 fields which each contain the correct access key:

WIAccessKey__c.String_Access_Key_Dev__c has a value of

2c072ad68ac3039fca9fa868a3033f95ea165213136f

WIAccessKey__c.String_Access_Key_Live__c has a value of

128jkg785788ddff559939fca9fa868a3033f95ea165

My question is, how do I update my Trigger code so that when the Trigger is used in Sandbox it uses the WILead__c.String_URL_Dev__c and WIAccessKey__c.String_Access_Key_Dev__c values, and when it is run in Production it uses the WILead__c.String_URL_Live__c and WIAccessKey__c.String_Access_Key_Live__c values?

Best Answer

First of all, I recommend you use a Hierarchy Custom Setting to store default configuration like you have here. They are better suited to the task than List Custom Settings. It's not clear based on your post which you are using.

Second, I would remove String from your field names. It is redundant and makes your code extra verbose. I also recommend strongly against separate fields for Dev/Live. That's why you're using a Custom Setting in the first place.

Third, Hierarchy Custom Settings have a getOrgDefaults() method, which is what you want here and why they are better suited to the task at hand.

MyWebhookConfig__c config = MyWebhookConfig__c.getOrgDefaults();
String url = config.URL__c;
String accessKey = config.accessKey;
Related Topic