Follwoing this post What is the best workaround for the 20 field history tracking cap?
I have tried to adapt it for my custom Object MPG__c where I want to track all fields. Tracking via field sets is a great idea without having to keep amending the apex. I have amended what I can based on my current custom object, my new MPGHistory__c customer object for field history and field set 'History Tracking' which is on MPG__c. I have built this in our Developer Pro sandbox but it is showing 0% coverage and when i tried to deploy to live I get: "Code Coverage Failure The following triggers have 0% code coverage. Each trigger must have at least 1% code coverage. MPGHistoryTracker"
Plus where is the relationship to MPG__c on the MPGHistory__c object so it is a related list on MPG__c object? :
trigger MPGHistoryTracker on MPG__c (after update) {
List<Schema.FieldSetMember> trackedFields = SObjectType.MPG__c.FieldSets.HistoryTracking.getFields();
if (trackedFields.isEmpty()) return;
List<MPGHistory__c> fieldChanges = new List<MPGHistory__c>();
List<string> apiNameList = new List<string>();
if(Trigger.isUpdate){
for (MPG__c aNew : trigger.new) {
MPG__c aOld = trigger.oldmap.get(aNew.Id);
for (Schema.FieldSetMember fsm : trackedFields) {
String fieldName = fsm.getFieldPath();
String fieldLabel = fsm.getLabel();
if (aNew.get(fieldName) != aOld.get(fieldName)) {
String oldValue = String.valueOf(aOld.get(fieldName));
String newValue = String.valueOf(aNew.get(fieldName));
if (oldValue != null && oldValue.length()>255) oldValue = oldValue.substring(0,255);
if (newValue != null && newValue.length()>255) newValue = newValue.substring(0,255);
MPGHistory__c aht = new MPGHistory__c();
aht.name__c = fieldLabel;
aht.apiName__c = fieldName;
aht.User__c = aNew.Id;
aht.ChangedBy__c = UserInfo.getUserId();
aht.OldValue__c = oldValue;
aht.NewValue__c = newValue;
apiNameList.add(aht.apiName__c);
fieldChanges.add(aht);
}
}
}
}
if (!fieldChanges.isEmpty()) {
insert fieldChanges;
}
}