Trigger Old Context Variables (oldMap, old)
Trigger
trigger LogTriggerOld on Account (after insert, after update, after delete, after undelete)
{
String BeforeOrAfter = (Trigger.isBefore ? 'Before' : 'After');
String TriggerType = ''
+ (Trigger.isDelete ? 'Delete' : '')
+ (Trigger.isInsert ? 'Insert' : '')
+ (Trigger.isUpdate ? 'Update' : '')
+ (Trigger.isUnDelete ? 'UnDelete' : '');
system.debug(BeforeOrAfter + ' ' + TriggerType
+ ': ' + 'Trigger.old == null ~ ' + (Trigger.old == null));
system.debug(BeforeOrAfter + ' ' + TriggerType
+ ': ' + 'Trigger.oldMap == null ~ ' + (Trigger.old == null));
}
Test
@IsTest
public class TestTriggerOld {
public static testmethod void InsertUpdateDeleteUndelete() {
Account a = new Account(Name='Test 1'); insert a;
a.Name = 'Test 2'; update a;
delete a;
undelete a;
}
}
Log results
USER_DEBUG|[11]|DEBUG|After Insert: Trigger.old == null ~ true
USER_DEBUG|[14]|DEBUG|After Insert: Trigger.oldMap == null ~ true
USER_DEBUG|[11]|DEBUG|After Update: Trigger.old == null ~ false
USER_DEBUG|[14]|DEBUG|After Update: Trigger.oldMap == null ~ false
USER_DEBUG|[11]|DEBUG|After Delete: Trigger.old == null ~ false
USER_DEBUG|[14]|DEBUG|After Delete: Trigger.oldMap == null ~ false
USER_DEBUG|[11]|DEBUG|After UnDelete: Trigger.old == null ~ true
USER_DEBUG|[14]|DEBUG|After UnDelete: Trigger.oldMap == null ~ true
USER_DEBUG|[11]|DEBUG|Before Insert: Trigger.old == null ~ true
USER_DEBUG|[14]|DEBUG|Before Insert: Trigger.oldMap == null ~ true
USER_DEBUG|[11]|DEBUG|Before Update: Trigger.old == null ~ false
USER_DEBUG|[14]|DEBUG|Before Update: Trigger.oldMap == null ~ false
USER_DEBUG|[11]|DEBUG|Before Delete: Trigger.old == null ~ false
USER_DEBUG|[14]|DEBUG|Before Delete: Trigger.oldMap == null ~ false
Trigger.Old is null in a Before Trigger and will therefore throw a NullPointerException for any reference / method invocation on it.
16:08:40.060 (60355000)|USER_DEBUG|[2]|DEBUG|**** Trigger.old null 16:08:40.060 (60362000)|SYSTEM_METHOD_EXIT|[2]|System.debug(ANY) 16:08:40.060 (60503000)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object