Is it possible for the trigger to see the name of the object it's firing for? Say can I make the OpportunityTrigger be aware that the object name it's firing for is Opportunity without hardcoding the object name in the code?


I want to use Custom Metadata to make Object_To_Track_mdt. Once a trigger fires I want to use the object name the trigger is firing for to see if the object needs to be tracked or not. Here's a very rough code sample I have in mind:

Object_To_Track__mdt trackedObject = [
                SELECT Id, 
                (SELECT Id FROM Fields_To_Track__r) 
                FROM Object_To_Track__mdt
                WHERE DeveloperName='Lead'
if (trackedObject  != null && trackedObject.Fields_To_Track__r.size() > 0) {
    // Verify if the modified fields for Lead need to be tracked or not.

If you don't care about the delete contexts, you can just do:

SObjectType triggerType = trigger.new.getSObjectType();

It doesn't add much complexity, however, to use a ternary to check for the null case:

SObjectType triggerType = trigger.isDelete ? 
    trigger.old.getSObjectType() :

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.