[SalesForce] Most efficient way to check if field belongs to Custom Setting list in Apex Trigger

I would like to know what is the most efficient way to loop through all fields in trigger a trigger so I can check against the field name for additional actions. I'm not sure how I can do this and would appreciate some advise.

Here is some pseudo code to help you understand what I'm trying to do:

// go through list of accounts
for(Account acc: Trigger.new) {

    // go through list of fields in Accounts
    // this is the section I'm not sure what the best way to go through fields
    for(FIELD : acc) { // <- not sure what to loop through

        // my logic for checking field against other logic

    }

}

Updated Code:

public static void matchedRecords(Map<Id, Account> triggerMapOld, Map<Id, Account> triggerMapNew){

    List<MyCustomSettingMonitor__c> customSetting = [SELECT Id, Field__c FROM MyCustomSettingMonitor__c];

    // go through each account record
    for(Account acc: triggerMapNew.values()) {

        for(MyCustomSettingMonitor__c customField : customSetting) {

            Object accountField = acc.get(customField.Field__c);
            system.debug('customField.Field__c: ' + accountField);

            // check if specified field has its value changed against Trigger.Old
            system.debug('old value:' + triggerMapOld.get(acc.Id).get(accountField));


        }

    }

}

Best Answer

It's probably better to iterate through the custom settings instead of the account fields, as there are probably less of them thus saving you iterations and making it more efficient.

Try something like this:

List<FieldSettings__c> settings = FieldSettings__c.getall().values();

for(Account acc: Trigger.new) {

    for(FieldSettings__c setting : settings) { 
        if (acc.get(setting.Field_Name__c) != Trigger.oldMap.get(acc.Id).get(setting.Field_Name__c)) {
            Object accountFieldvalue = acc.get(setting.Field_Name__c);
            // do what you need to do with the value
        }
    }

}
Related Topic