function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Swamy PSwamy P 

how to compare old and new values dynamically for all the fields

Hi Buddies,

I have a scenario based on the triigger, i.e, compare old and new values if it is changed send a mail to group of users.
It is not only for a single field, its for all fields i.e, mostly 200 fields.

So for this am using dynamic apex and comparing all fields, but I was not able to compare.

Map<String,Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
          Schema.SObjectType leadSchema = schemaMap.get('Order__c ');
          Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

for (String fieldName: fieldMap.keySet()) {                    
                        for(Order__c w:Trigger.New){
                            string subject='';
                            string body='Changed Values for Record: '+w.name;  
                            if(Trigger.oldMap.get(w.id).fieldName!=Trigger.newMap.get(w.id).fieldName){ -->Error Line
                              body='<p>Hi,</p>';
                              body+='Your Record: '+w.name+' , Got changes value from <b>'+Trigger.oldMap.get(w.id).fieldName;
                              body+='</b> to <b>'+Trigger.newMap.get(w.id).fieldName;
                              mail.setHtmlBody(body);
                              mail.setSubject(subject);
                              allMails.add(mail);
                              Messaging.sendEmail(allMails);
                            }
                        }
                   }

Error is like : Error: Compile Error: Invalid field fieldName for SObject Order__c at line 69 column 76

its because, Trigger.oldMap.get(w.id).fieldName only. How can i pass this?
Best Answer chosen by Swamy P
Subhash GarhwalSubhash Garhwal
Hi Padayappa(Swamy),

To compare fields values dynamically you need to get these values 
Like 

Trigger.oldMap.get(w.id).get(fieldName) and Trigger.newMap.get(w.id).get(fieldName)

Regards
Subhash