Skip to main content The Trailblazer Community will be unavailable from 2/1/2025 to 2/2/2025. Please plan your activities accordingly.
error

We made a wrong turn. Try again.

Attempt to de-reference a null object - Need Help with Trigger

Hi, 

I need help with a trigger. Someone please help me on what I am doing wrong. Thank you.

My scenario is - For a person Account - Address, City & Zip are filled.

When a Case is created for that Customer - Address, City & Zip should automatically be filled. So that Sales reps don't have to fill those 3 fields again.

Here is my CODE

trigger CasesTrigger on Case (after insert){

    Set<Id> accIds = new Set<Id>();

    List<Case> lstCases = new List<Case>();

    for(Case objCase:trigger.new){

        accIds.add(objCase.AccountId);

        system.debug('ACCOUNTIDS'+accIds);

    }

    Map<ID, Account> MapAccIdtoAccount = new Map<ID, Account>([Select Id, Street__c, City__c, State__c, Zip__c from Account where Id IN:accIds]);

system.debug('ACCOUNTSMAP'+MapAccIdtoAccount);

    for(Case objCase:Trigger.new){

        Case oCase = new Case();

       

    if(MapAccIdtoAccount.containsKey(objCase.AccountId))

{

         oCase.Address_Line1__c = MapAccIdtoAccount.get(oCase.AccountId).Street__c ;

            system.debug('ADDRESS---'+oCase.Address_Line1__c); 

           oCase.City__c = MapAccIdtoAccount.get(oCase.AccountId).City__c ;

            oCase.State__c = MapAccIdtoAccount.get(oCase.AccountId).State__c ;

           oCase.Zip__c = MapAccIdtoAccount.get(oCase.AccountId).Zip__c ;

        lstCases.add(oCase);

         system.debug('oCASE'+oCase); 

            }

            }

    if(lstCases.size()>0){

        update lstCases;

    }

}
7 answers
  1. Sep 23, 2015, 6:31 PM
    Since you're instantiating a new Case object to do the update, you'll need to include the Id of the Case from the trigger.

    Change the first line of your for-loop to this:

     

    Case oCase = new Case(Id = objCase.Id);

    Hope that helps,

    Clint
0/9000