Modify Trigger Using Custom Settings

Introduction

When there is a requirement to deactivate the trigger in production, we can first deactivate the trigger into the sandbox environment and then deploy it using change sets. But this isn’t a good practice to be considered as this would take a longer time in deactivating triggers. So, there is another approach or concept through which we can directly deactivate triggers in production, which is none other than using Custom Settings.

When do we need to modify triggers during runtime?

We can modify triggers when we want that trigger to be used for a specific user or profile. Like, we can set a flag as true for some users in a custom hierarchical setting and if the flag is true, run the specified trigger; if the flag is false, don’t run the trigger.

What are custom settings?

Custom settings data is stored in the cache memory so that it becomes easily accessible, and no server trip to access the data is needed.

Custom settings are more like Custom Metadata having some differences like custom settings data is not deployable but we can deploy custom metadata.

We have two types of custom settings:

List – same data is accessible for every user in org irrespective of profiles or users

Hierarchy – different users can have different values based on the profile or user.

Custom settings allow developers to change the value of the data stored based on the currently running user and change the functionality of trigger like activating or deactivating it.

How to Modify Trigger using Custom Settings?

For this, we first need to create a custom setting definition, then under that, create a checkbox (Boolean) field for each object we have a trigger that we want to bypass. After this, click the ‘Manage’ button present at the top of the custom setting to create records for it. Now, we can use custom settings in the trigger to bypass it.

Example: Create a record of Opportunity object whenever Account record is created with Industry as ‘Banking’.

if(TestObject__c.getInstance('Active Rec').ActivateTheTrigger__c){
//code when condition is met
}
In this, TestObject__c is the custom setting
getInstance returns single record, here - 'Active Rec'

ActivateTheTrigger__c is the checkbox field on the mentioned record.

Now, if we want to deactivate the trigger, mark it ActivateTheTrigger__c unchecked. The trigger will be deactivated.

Example

trigger AccOppTrigger on Account (after insert) {
if(TestObject__c.getInstance('Active Rec').ActivateTheTrigger__c){
List oppRec = new List();
for(Account acc : Trigger.new){
if(acc.Industry == 'Banking'){
Opportunity opp = new Opportunity(Name = acc.Name,
StageName = 'Prospecting',
AccountId = acc.Id,
CloseDate = Date.today().addDays(15));
oppRec.add(opp);
 }
}
if(!oppRec.isEmpty()){
insert oppRec;
  }
 }
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.