1

I am having a custom object with 470 fields in it. And in After update trigger I am making some call outs. If a value is changed in any of the field then I need to have lengthy check for all the fields which is not correct approach.

Its taking time to compare the new value with old value to find out whether the value is changed.

I feel this is not the proper way to do it.

7
  • Do you have to know which field(s) changed?
    – Phil W
    May 23, 2021 at 16:33
  • Do you need to compare all the 470 fields? May 23, 2021 at 16:33
  • @PhilW Yes. I want to know if there is any change in field. and if there is any change then only I have to make call out May 23, 2021 at 16:37
  • 1
    So just use SObject equality between the old and new representations to see if any field changed value.
    – Phil W
    May 23, 2021 at 17:31
  • 1
    If you have total 470 fields and you need to make a call out if any of the field changed then you can direct call your API in after update trigger without comparing anything. Because update trigger only runs if there is any update to the record. May 23, 2021 at 19:02

1 Answer 1

5

To easily look for any significant change, you can just:

Id[] changedRecordIds = new Id[0];
for(Integer i = 0, s = Trigger.new.size(); i < s; i++) {
  sObject oldRecord = Trigger.old[i].clone(true, false, false, false);
  sObject newRecord = Trigger.new[i].clone(true, false, false, false);
  if(oldRecord != newRecord) {
    changedRecordIds.add(Trigger.new[i].id);
  }
}

You can also restrict it to just specific fields by obtaining a list of field names, in order to filter out unwanted fields:

Set<String> allowlist = new Set<String>{ 'Name','Field1','Field2' };
Id[] changedRecordIds = new Id[0];
for(Integer i = 0, s = Trigger.new.size(); i < s; i++) {
  Map<String, Object> oldRecordFields = Trigger.old[i].clone(true, false, false, false).getPopulatedFieldsAsMap();
  Map<String, Object> newRecordFields = Trigger.new[i].clone(true, false, false, false).getPopulatedFieldsAsMap();
  oldRecordFields.keySet().retainAll(allowlist);
  newRecordFields.keySet().retainAll(allowlist);
  if(oldRecordFields != newRecordFields) {
    changedRecordIds.add(Trigger.new[i].id);
  }
}

You could use a Field Set to specify the values, too, or you could make a removeList that uses removeAll to specifically exclude fields, if you prefer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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