How to compare the old and new values in a trigger for multiple fields?

I have 30+ fields in a field set, and in the update part of my trigger, I want to see if any of those fields have been changed. Can I access them using field sets? Anyway to do it, short of writing out every field in my trigger?

I’m doing something similar to this: http://techman97.wordpress.com/2011/10/22/comparing-new-values-vs-old-values-in-apex-trigger/

Answer

I am not sure if you could use the field set directly to compare but you can use the sObject’s get method to do the job

set<String> fieldSet = new Set<String>();
//dynamically get the fields from the field set and then use the same for comparison in the trigger. 
for(Schema.FieldSetMember fields :Schema.SObjectType.Account.fieldSets.getMap().get('yourFieldSetName').getFields()){
    fieldSet.add(fields.getFieldPath());
}
for(account a: trigger.new){
    set<String> changedFieldSet  = new Set<String>();
    for(string s: fieldSet){
        if(a.get(s) != trigger.oldMap.get(a.Id).get(s)){
            changedFieldSet.add(s);//adding fields whose value changed
        }
    }
    if(changedFieldSet.size()>0){
        //do something
    }
}

Attribution
Source : Link , Question Author : PartOfTheOhana , Answer Author : Tushar Arora

Leave a Comment