I have two fields "Cost, Quantity" to which I need to check if values are changed - In the future, some fields will get added to this list.

I don't want to change the trigger every time if new fields are added. So, I thought of adding a Custom Label with field API "Cost__c, Quantity__c" and iterate this in Trigger to check Old and New values with single If condition. But this is not working as expected. Below is the sample code,

Custom Label : Account_History_Tracking_Fields
Values : Quantity; Cost

Sample Code

string HistoryFields = System.Label.Account_History_Tracking_Fields;
list<string> AccountHistoryFields =  HistoryFields.split(';');

for(Account accx : Trigger.new)
  Account oldAccount = Trigger.oldMap.get(accx.ID);

   for(string AccField : AccountHistoryFields)
      // I need something like below condition - which compares all custom label values with single If condition
       //if(accx.AccField != oldAccount.AccField)


Is there a way to do this?

2 Answers 2


Use a Field Set, instead. That's one of their primary purposes. Your code can then be written as follows:

for(Integer i = 0, s = Trigger.new.size(); i < s; i++) {
  sObjectField[] changes = new sObjectField[0];
  for(Schema.FieldSetMember member: Schema.sObjectType.ObjectName__c.fieldSets.fieldSetName.getFields()) {
    sObjectField field = member.getsObjectField();
    if(Trigger.old[i].get(field) != Trigger.new[i].get(field)) {
  if(!changes.isEmpty()) {
    // Do stuff here //

This is not what Custom Labels are for. Instead, use Custom Metadata records, or a List Custom Setting. Custom Metadata can be deployed with your trigger, but requires more care in constructing unit tests; List Custom Settings cannot be deployed, but are easily constructed in tests.

Your code doesn't work because you cannot access sObject properties dynamically by using a string variable as a property name:

   if(accx.AccField != oldAccount.AccField)

Instead, you need to use the sObject methods get(apiName) and put(apiName, value). Note that both methods use generically-typed Object values, so you'll need to cast the return value of get() to a concrete type if you want to interact with it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .