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
ArunaAruna 

Dynamically check some fields data changed in apex trigger --> High priority

Hello everyone,

We do have requirement where in trigger need to check only some fields changed in the trigger dynamically.
I know generally we do by using old and new values in trigger to check if the field values are changed.
Oldmap.Fieldname__c!=new.FieldName__c
But our requirement instead of using field in the code dynamically need to get only some field and check if they have changed the data.
That means we do not want list each and every field api name .
Want to get field API name with old and new values dynamically.
is this possible.
I was looking at some blog where we can get all the fields but I want only some fields
https://developer.salesforce.com/forums/?id=906F00000008xFXIAY

is this possible to get dynamically get only get couple of fields changed in the apex code (trigger) if it can any on please send sample code.
AbhishekAbhishek (Salesforce Developers) 
Try this Sample Code,

trigger UpdateTriggerSample_tgr on Lead (after update) { Lead NewLead = trigger.new[0]; Lead OldLead = trigger.old[0]; Lead LeadObject = new Lead(); // This takes all available fields from the required object. Schema.SObjectType objType = LeadObject.getSObjectType(); Map<String, Schema.SObjectField> M = Schema.SObjectType.Lead.fields.getMap(); for (String str : M.keyset()) { try { System.debug('Field name: '+str +'. New value: ' + NewLead.get(str) +'. Old value: '+OldLead.get(str)); if(NewLead.get(str) != OldLead.get(str)){ system.debug('******The value has changed!!!! '); // here goes more code } } catch (Exception e) { System.debug('Error: ' + e); } } }

I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.