0

Please let me know the reason for record captures for delete operation failing here.

Code:

trigger AccountHistoryTracker on Account (after update,after delete) {
    List<Schema.FieldSetMember> trackedFields = SObjectType.Account.FieldSets.HistoryTracking.getFields();

    if (trackedFields.isEmpty()) return;

    List<AccountHistoryTracking__c> fieldChanges = new List<AccountHistoryTracking__c>();

    List<string> apiNameList = new List<string>();        

   // if(Trigger.isUpdate|trigger.isdelete){

        for (Account aNew : trigger.isDelete ? trigger.Old : trigger.new) 
        {
            Account 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));

                    AccountHistoryTracking__c aht = new AccountHistoryTracking__c();
                    aht.name         = fieldLabel;
                    aht.apiName__c   = fieldName;
                    aht.User__c = UserInfo.getUserId();
                    aht.OldValue__c  = oldValue;
                    aht.NewValue__c  = newValue;
                    aht.createddate__c = system.now();
                    aht.Account__c = aNew.Id;

                    apiNameList.add(aht.apiName__c);
                    fieldChanges.add(aht);
                }        
            }
        }
    //}

    try{
        if (!fieldChanges.isEmpty()) {
            insert fieldChanges;
        }
    }catch(DMLException e){
        System.debug(e.getMessage());    
    }
}
3
  • which is line 16? Its most likely that aOld.get(fieldName) or aNew.get(fieldName) is returning null.
    – Prady
    Sep 10 '14 at 10:16
  • Sorry Prady! here is the faulty line. for (Account aNew : trigger.new) Sep 10 '14 at 10:17
  • 1
    Delete trigger cannot have a trigger.new. It would use only trigger.old
    – Prady
    Sep 10 '14 at 10:36
2

Delete trigger cannot have a trigger.new. It would use only trigger.old. You would need to separate the logic for update and delete or use something like this

for(Opportunity opp : trigger.isDelete ? trigger.Old : trigger.new){

as used by techtrekker in his answer to this question After Delete - Need To "Cleanup" When An Opp Is Deleted

2
  • Hi Prady still it fails to capture changes. Edited the question to give you the whole code. Please let me know my fault. Sep 10 '14 at 11:19
  • What is the error you are getting
    – Prady
    Sep 10 '14 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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