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
Chris HeathChris Heath 

Receiving Error on update: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

Hello,

I am receiving this error on a clip of test code after writing a different trigger...

"System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TrainingFellowshipPatientUpdate: execution of AfterInsert caused by:
System.NullPointerException: Attempt to de-reference a null object Trigger.TrainingFellowshipPatientUpdate: line 5, column 1: []"

Account a = new Account();
a.Name = 'Test Name';
insert a;

Here is the trigger with the numbered line bolded:

trigger TrainingFellowshipPatientUpdate on Account (after insert, after update) {

for (Account pt: trigger.new) {
 
  Account old = Trigger.oldMap.get(pt.Id);
 
  if (pt.OwnerId != old.OwnerId) {
   //User u = [SELECT Id FROM User WHERE Id = :pt.OwnerId];
   
   Training_Fellowship__c tf = new Training_Fellowship__c();
  
   //if(pt.OwnerId != null) {
   tf = [SELECT Id FROM Training_Fellowship__c WHERE User__c = :pt.OwnerId LIMIT 1];
   //}
  
   if (tf != null) {
    pt.Training_Fellowship__c = tf.Id;
   } else {
    pt.Training_Fellowship__c = null;
   }
   update pt;
  }
}
}

Could somebody please help me with this?

Thank you in advance!
Best Answer chosen by Chris Heath
Vinit_KumarVinit_Kumar
I see so many issues with your code :-

1.)  You are running SOQL inside for Loop.
2.) You are performing DML inside FOR loop.
3.) Trigger is on After event and the record would be read-only,hence you can't update it.
4.) This line would be always be null for insert event as Trigger.old is not available in insert events which you are facing in your test class.

Account old = Trigger.oldMap.get(pt.Id);

I would suggest to modify your Trigger based on my findings.

Hope this helps.

All Answers

Edwin VijayEdwin Vijay
Can you not make the trigger before insert, before update and remove the update statement in the trigger?
Vinit_KumarVinit_Kumar
I see so many issues with your code :-

1.)  You are running SOQL inside for Loop.
2.) You are performing DML inside FOR loop.
3.) Trigger is on After event and the record would be read-only,hence you can't update it.
4.) This line would be always be null for insert event as Trigger.old is not available in insert events which you are facing in your test class.

Account old = Trigger.oldMap.get(pt.Id);

I would suggest to modify your Trigger based on my findings.

Hope this helps.
This was selected as the best answer