function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tasia Demuth 4Tasia Demuth 4 

System.NullPointerException: Attempt to de-reference a null object: ()".

Hi!

We have customer service cases related to the lead object. I am trying to write a trigger that updates any cases associated to leads that have been deleted. Below is my code. 

I get the error message: System.NullPointerException: Attempt to de-reference a null object: ()".
Any help is greatly appreciated!

Thanks, 
Tasia

trigger UpdateCaseWhenLeadDeleted on Lead (before delete) {
if(Trigger.isBefore && Trigger.isDelete)
    {
       List<Case> listCase = new List<Case>();
        Set<Id> DeletedLeads = new Set<Id>();
        for(Lead objLead : Trigger.new)
        {
            if(objLead.isDeleted)
                DeletedLeads.add(objLead.Id);
        }
        for(Case objCase : [SELECT Lead__c FROM Case WHERE Lead__c IN : DeletedLeads])    
        {
            objCase.Lead__c = null;
            objCase.Status = 'Declined';
            listCase.add(objCase);
        }
        update listCase;
    }
}
Best Answer chosen by Tasia Demuth 4
Neetu_BansalNeetu_Bansal
Hello Tasis,

Trigger.new is not available on before delete, and after delete triggers.  Use Trigger.old instead.

Please mark this as best answer, if it helps.

Thanks,
Neetu

All Answers

Neetu_BansalNeetu_Bansal
Hello Tasis,

Trigger.new is not available on before delete, and after delete triggers.  Use Trigger.old instead.

Please mark this as best answer, if it helps.

Thanks,
Neetu
This was selected as the best answer
Alain CabonAlain Cabon
Neetu_Bansal has already posted the exact right answer.

A little trap of Salesforce because the trigger can be saved without warnings.

Its is a common error:  https://developer.salesforce.com/forums/?id=906F00000008vh3IAA

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables_considerations.htm
Tasia Demuth 4Tasia Demuth 4
Thank you both! That appears to have solved the error issue! 

I am still having trouble with the Status not updating. Is there something I am missing for setting picklist values? 

Thank you again and let me know if there is a quick fix for the picklist values. 
Neetu_BansalNeetu_Bansal
Hello Tasia,

Remove this check if(objLead.isDeleted), this is before insert and record is still not deleted, so it is false always.

Thanks,
Neetu
Tasia Demuth 4Tasia Demuth 4
Yes that totally worked! 

Thanks so much! I really appreciate your help. 

Tasia