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
Semira@gmail.comSemira@gmail.com 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, NewJobTimeStampOnAccount: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object

Hi I have written a trigger that will update a field on Account when the child record is created or the first child records (on Account) will get updated. However, my test class is failing on the de-refence a null object and I'm getting 91% coverage. how? 

Error Message:

System.DmlException: Upsert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, NewJobTimeStampOnAccount: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.NewJobTimeStampOnAccount: line 22, column 1: []

Trigger:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
trigger NewJobTimeStampOnAccount on Job__c (after insert, after update) {

  Map<ID, Account> parentAcct = new Map<ID, Account>(); //Making it a map instead of list for easier lookup
  List<Id> listIds = new List<Id>();
 
if(trigger.isInsert || trigger.isUpdate){
  for (Job__c childObj : Trigger.new){
    listIds.add(childObj.Account__c);
  }
}
  //Populate the map. Also make sure you select the field you want to update, amount
  //The child relationship is more likely called jobs__r (not job__r) but check
  //You only need to select the child jobs if you are going to do something for example checking whether the job in the trigger is the latest
  parentAcct = new Map<Id, Account>([SELECT id, New_Job_Start_Date__c, (SELECT ID, Date_Time_Taken__c FROM Jobs__r) FROM Account WHERE ID IN :listIds]);
 
  List<Job__c> i = [select id from Job__c where Account__c in :listIds order by Date_Time_Taken__c ASC limit 5];

  for (Job__c job: Trigger.new){
     if(i[0].id == job.id)
     {
        Account myParentAcct = parentAcct.get(job.Account__c);
        myParentAcct.New_Job_Start_Date__c = job.Date_Time_Taken__c;
       
     }
  }
  update parentAcct.values();

}

Test class:

@isTest
private class NewJobTimeStampOnAccount_Test {

    static testmethod void test_trigger(){
     
        Job__c job = new Job__c(Job_Name__c = 'Roy,Semira tes', Date_Time_Taken__c = datetime.now(), contact__c = '003S000000m4qD5', Account__c = '001S000000gq5Dp', Project_manager__c = '00570000002rgiK', name = '6##-##-02206', Stage__c = 'Qualification', Status__c = 'Opportunity', Office__c = 'Chicago', Lead_Source__c = 'Agent', Job_class__c = 'Apartment', County__c = 'Orange', City_of_LA__c = 'No');
      
        upsert job;
      
    }
}
Best Answer chosen by Semira@gmail.com
Semira@gmail.comSemira@gmail.com
I figured it out why. All I need was this.

for (Job__c job: Trigger.new){
     if(i[0].id == job.id)
     {
        Account myParentAcct = parentAcct.get(job.Account__c);
      if(myParentAcct != null)
        myParentAcct.New_Job_Start_Date__c = job.Date_Time_Taken__c;
      
     }
  }
  update parentAcct.values();

And I needed to specify in test class because it is calling another trigger which is checking for previous number. 

job.Job_Number__c = '000-00-00034';
job.Name = '000-00-00034';

It is working perfectly fine with 92% code coverage. Thank you for your help @Ramu_SFDC. 

All Answers

Ramu_SFDCRamu_SFDC
The only issue I can sense is that the list size of i is never checked but the comparison is made. Please modify the code as below (bold text represents the changes)

trigger NewJobTimeStampOnAccount on Job__c (after insert, after update) {

  Map<ID, Account> parentAcct = new Map<ID, Account>(); //Making it a map instead of list for easier lookup
  List<Id> listIds = new List<Id>();

if(trigger.isInsert || trigger.isUpdate){
  for (Job__c childObj : Trigger.new){
    listIds.add(childObj.Account__c);
  }
}
  //Populate the map. Also make sure you select the field you want to update, amount
  //The child relationship is more likely called jobs__r (not job__r) but check
  //You only need to select the child jobs if you are going to do something for example checking whether the job in the trigger is the latest
  if(listids.size()>0){
  parentAcct = new Map<Id, Account>([SELECT id, New_Job_Start_Date__c, (SELECT ID, Date_Time_Taken__c FROM Jobs__r) FROM Account WHERE ID IN :listIds]);

  List<Job__c> i = [select id from Job__c where Account__c in :listIds order by Date_Time_Taken__c ASC limit 5];
if(i.size()>0){
  for (Job__c job: Trigger.new){
     if(i[0].id == job.id)
     {
        Account myParentAcct = parentAcct.get(job.Account__c);
        myParentAcct.New_Job_Start_Date__c = job.Date_Time_Taken__c;
     
     }
  }
  update parentAcct.values();
  } //end of if(i[0].id == job.id)
//end of if(listids.size()>0)
}

Let me know if this fixed the issue. 
Semira@gmail.comSemira@gmail.com
Well, it's not giving me error when I run/compile the code. It's giving me error on the Test class. Right now, it's failing at other triggers written priviously. Now, those triggers are written by other admins before me at my company. I tried writing my code in a way that even though it cause other triggers to go off, it should not fail. Unfortunately, the test class is failing over and over with the same de-refencing null object. 

Question: when I run my test, should I be turning off all the other triggers and test it? Also, when I deploy should I deactivate all the other triggers? This is my first time writing and deploying code so I'm not too familier with the fomalities. 
Semira@gmail.comSemira@gmail.com
I figured it out why. All I need was this.

for (Job__c job: Trigger.new){
     if(i[0].id == job.id)
     {
        Account myParentAcct = parentAcct.get(job.Account__c);
      if(myParentAcct != null)
        myParentAcct.New_Job_Start_Date__c = job.Date_Time_Taken__c;
      
     }
  }
  update parentAcct.values();

And I needed to specify in test class because it is calling another trigger which is checking for previous number. 

job.Job_Number__c = '000-00-00034';
job.Name = '000-00-00034';

It is working perfectly fine with 92% code coverage. Thank you for your help @Ramu_SFDC. 
This was selected as the best answer
wittenrawittenra
Hi, I have the same error message, but I am not sure, what else to take care of.
My Code is the following and the error is in a test class

My Code:
trigger AddAccEuroAISNo on Task (before insert, before update) {
    for (Task a : trigger.new){	
      Case check = [Select Subject from Case where ID = :a.WhatId];
        if(check.Subject != 'MergeTest3') {
        String WhoIdString = String.valueof(a.WhoId);
            if(Task.WhoId != null){
            if (WhoIdString.substring(0,3) == '003'){
                    if(Task.WhoId != null){
                Contact parent = [SELECT AccountId, Account.Name, Name, EuroAIS_Customer_Number__c  FROM Contact WHERE ID = :a.WhoId ];
                if(parent.AccountId  != null){
                a.Account__c = parent.Account.Name;
                a.EuroAISCustomerId__c = parent.EuroAIS_Customer_Number__c;
                a.Contact__c = parent.Name;
                }}}}}}}

The Error Message:

Test_MergeCasesController.caseMergeTestMethod(), Details: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddAccEuroAISNo: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.AddAccEuroAISNo: line 7, column 1: [] Class.MergeCasesController.mergeCases: line 181, column 1 Class.Test_MergeCasesController.caseMergeTestMethod: line 48, column 1


Thanks a lot in advance for any help
 
Pavel Zaverach 11Pavel Zaverach 11
Hi, I Have Trigger 
trigger ContactTrigger on Contact (after insert) {
 
  list<Case> cases = new list<Case> ();
  Set<Id> accIds = new Set<Id>(); 
  
  for (Contact cont : Trigger.newMap.values()) {
            accIds.add(cont.AccountId);
          }
        Map<Id,Account> mapIdToAcc = new Map<Id,Account>([SELECT Id,OwnerId FROM Account WHERE Id IN :accIds]);
        for (Contact cont : Trigger.newMap.values()) {
          
            if (cont.Contact_Level__c.contains('Primary')){
                
			cases.add(new Case(ContactId=cont.Id, Status = 'Working', 	Origin = 'New Contact',  Priority = 'High', OwnerId=mapIdToAcc.get(cont.AccountId).OwnerId));                
            }
            
            if (cont.Contact_Level__c.contains('Secondary')){
                
			cases.add(new Case(ContactId=cont.Id, Status = 'Working',  Origin = 'New Contact',  Priority = 'Medium', OwnerId=mapIdToAcc.get(cont.AccountId).OwnerId));                
            }
            
            if (cont.Contact_Level__c.contains('Tertiary')){
                
			cases.add(new Case(ContactId=cont.Id, Status = 'Working',  Origin = 'New Contact',  Priority = 'Low', OwnerId=mapIdToAcc.get(cont.AccountId).OwnerId));                
            }
       
        }
        insert cases;
    }

and Test Class
@isTest

private class CotnactTriggerTest {
    
    
    @isTest public static void CotnactTriggerTest () {
        
       Account accnt = new Account( Name='TestAccount');
        insert accnt;
        
       List<Contact> conlist = new List<Contact>();
        
        Contact con1 = new Contact(FirstName = 'Willy', LastName = 'Skot', Email = 'wlwl@wfgfwlwlw.com',
                                   Contact_Level__c = 'Primary', AccountId = accnt.Id);
        
        Contact con2 = new Contact(FirstName = 'Leo', LastName = 'Messi', Email = 'LM@LMf.com',
                                   Contact_Level__c = 'Secondary', AccountId = accnt.Id);
        
        Contact con3 = new Contact(FirstName = 'Aladin', LastName = 'Bayburin', Email = 'AB@wAB.com', 
                                   Contact_Level__c = 'Tertiary', AccountId = accnt.Id);
       	
        Contact con4 = new Contact(FirstName = 'Telek', LastName = 'Japak', Email = 'TL@JP.com',
                                AccountId = accnt.Id);
        
        	conlist.add(con1);
            conlist.add(con2);
           	conlist.add(con3);
        	conlist.add(con4);  
        	insert conlist; 
 
        List <Case> cases = [SELECT Id, OwnerID, Status, Origin, Priority FROM Case ];
        
        Case case0 = cases.get(0);
        Case case1 = cases.get(1);
        Case case2 = cases.get(2);
        Case case3 = cases.get(3);
        System.assert(case0.Priority == 'High', true);
        System.assert(case1.Priority == 'Medium', true);
        System.assert(case2.Priority == 'Low', true);
        System.assert(case3.Priority == 'Medium', true);
        
        System.assert(con1.AccountId == case0.AccountId,true);
        System.assert(con2.AccountId == case1.AccountId,true);
        System.assert(con3.AccountId == case2.AccountId,true);
        System.assert(con4.AccountId == case3.AccountId,true);
        
        System.assert(case0.ContactId == con1.Id);
        System.assert(case1.ContactId == con2.Id);
        System.assert(case2.ContactId == con3.Id);
        System.assert(case3.ContactId == con4.Id);
 
     
    
    }
    

}

Error: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactTrigger: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0 with id 500f200001H1ixdAAB; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Trigger.ContactTrigger: line 27, column 1: []

I do not now, when is problem! Help will me!!!!!
Semira@gmail.comSemira@gmail.com
First of all, you should always write a helper class and call it from your trigger. (best practice) 

2ndly, write your loops like this:

Contact cont : Trigger.new (since you are writing your code in the trigger insdead of helper class). 

3rd, check for that MapIdToAcc for null value. So after the for loop add another IF condition to check whether the map is null. Only execute the condition if map has a value. 

Try that and see what happens. 
Rahul H 4Rahul H 4
Same error on my trigger 
i am trying contact name to be populated with customer name when a case is created. the trigger gets saved without any compilation error however when I am creating a Case and saving it, throws error 

case: execution of BeforeInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

Trigger:
​========
​​​​​​
trigger Images34_case on Case (before insert, before update) {
Case caseToAdd = new Case();
caseToAdd.subject = 'dean'; 
// caseToAdd.contact.name = 'Something'; 
insert caseToAdd; 
system.debug(caseToAdd); 
List<case> clist = new List<case>(); 
clist.add(caseToAdd); 
// finding the contact with which the contact name needs to be populated 
contact c= [select id from contact where name ='Customer_Name__c']; 
for( case ca : clist) 

//Associating contact Id 
ca.contactid=c.id; 

system.debug('kaka'+clist); 
database.DMLOptions dmo = new database.DMLOptions(); 
update (caseToAdd); 
}