[SalesForce] Activate/Deactivate Apex Trigger using custom object configuration

I need to control whether a trigger can execute or not without using the standard salesforce checkbox in each of the trigger's page.
I have a custom object populated with the trigger ids present in an instance and have a custom field set against each of the trigger id stating active or inactive. But from within the trigger i am unable to query that object because i do not know the id of the trigger which is executing. If i could find the trigger id, i can check against that object and find if this trigger can execute or not.

Any solution or workaround for this will be very helpful.

Best Answer

Querying for Apex Triggers: In answer to your question you can execute the following to list the triggers associated with the object being operated on. The only context you have is the object itself however, so you may need to add further criteria to the query to narrow it down to your specific trigger.

// Query ApexTriggers for this object (add NamespacePrefix or Name criteria to narrow this search)
String triggerSObjectName = 
    Trigger.isInsert ?
        Trigger.new[0].getSObjectType().getDescribe().name :
List<ApexTrigger> triggersForThisObject = 
    [select Id, Name from ApexTrigger where TableEnumOrId = :triggerSObjectName ];
System.debug('First trigger Id ' + triggersForThisObject[0].Id);

Another Consideration: Since you have to add the code to disable the trigger, have you considered using the trigger name (as a convention) instead of its ID. Then using a Custom Setting instead of a Custom Object. Which will be not use any SOQL queries. Further more (optionally) if your creating a managed package, a protected custom setting is only visible to your support team, and thus admins cannot disable.

The following trigger code sample below uses a List based Custom Setting.

trigger TestTrigger on Test__c (before insert, before delete) {

    if(TriggerControl__c.getValues('TestTrigger') != null)

This custom setting does not have any fields beyond the Name field. So long as a record exists with the appropriate name the above code will disable the trigger. You could extend this with other fields that control your trigger behaviours.

enter image description here

Related Topic