You need to sign in to do that
Don't have an account?
David S
Trigger to monitor field updates
Hello. I have created a trigger to minotor if certain fields are updated in a custom object. If the field is updated it creates a record in another custom object. Below is the code:
trigger CheckFieldUpdate on Obj1__c (before update) { List<Obj1__c> stores = trigger.new; List<Obj2__c> tasks = new List<Obj2__c>(); for(Obj1__c s : stores){ if(s.Field1__c <> trigger.oldMap.get(s.id).Field1__c) { Obj2__c tsk = new Obj2__c( Company__c = s.id, Name = 'Changed Field1 from "'+ trigger.oldMap.get(s.id).Field1__c +'" to ' + '"' + s.Field2__c + '"' ); tasks.add(tsk); } if(s.name <> trigger.oldMap.get(s.id).name) { Obj2__c tsk = new Obj2__c( Company__c = s.id, Name = 'Changed Field2 from "'+ trigger.oldMap.get(s.id).Field2__c +'" to ' + '"' + s.Field2__c + '"' ); tasks.add(tsk); } if (!tasks.isEmpty()) { insert tasks; } }
The code above only checks for 2 fields. What if there are more fields that i need to check, i'm wondering if there is a way to accomplish this in more efficient manner? Is it possible to create a loop to go though a list of fields?
Thanks.
You could us hierarchial custom setting here. And in its name field put the csv field names and in your trigger access the custom setting and prepare list of Field names.
Below is the pseudo code, Hope it helps you ion understanding custom settings:
All Answers
For making the list of string configurable you could either use field sets or custom setting(store comma separated field names it).
Thanks for the response Rahul. I have very limited experience with custom settings, but it sounds like that could work. Would you be able to provide a small example on how you would use it in Apex trigger?
Thanks,
David
You could us hierarchial custom setting here. And in its name field put the csv field names and in your trigger access the custom setting and prepare list of Field names.
Below is the pseudo code, Hope it helps you ion understanding custom settings:
Hi Rahul,
I also have similar requirement.Do I have to create custom field names in the custom settings with the same API names which I have created in objects in salesforce.
Can u advise.
Thanks,
Hi Rahul,
I was able to get the code to work with a test List of string first. When I tried to use the custom setting list, i get the following error message:
The line its referring to following if statement:
Did I incorrectly setup my custom setting?
Thanks,
David
In the above code, I have defined the custom setting with Name CheckFieldUpdate__c. In its Name field you need to add the Field API names in CSV format.
Example:
In custom setting CheckFieldUpdate's Name field enter value as
In my original post I had commented the Custom setting part.
Refer this for Managing Custom Settings Data.