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
hoomelhoomel 

Problem with trigger on User object

Hello,

 

as I am aware, Triggers on the User object are a bit 'hinky' but a customer had a requirement for a trigger.

 

This is the Trigger I wrote:

trigger userTrigger on User (before insert, before update) {
	private User[] newUser = Trigger.new;
	private User[] oldUser = Trigger.old;
	
	if(oldUser[0].isActive == false && newUser[0].isActive == true){
		newUser[0].Last_Inactive__c = System.now();
	}
	if(oldUser[0].isActive == true && newUser[0].isActive == false){
		newUser[0].Last_Active__c = System.now();
	}
}


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

Trigger.userTrigger: line 5, column 1: []    Plasma_Production        line 1    Force.com run test failure

What can I do about it? I am currently out of ideas how to get around this error.

 

Thanks in advance,

hoomel

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard
Trigger.old won't be populated for a before insert trigger, as there isn't an old version in the database. Only the trigger.new will be populated in that case.

All Answers

bob_buzzardbob_buzzard
Trigger.old won't be populated for a before insert trigger, as there isn't an old version in the database. Only the trigger.new will be populated in that case.
This was selected as the best answer
jbroquistjbroquist
Yeah I would just remove the before insert part of your trigger and only run it before update. Last_Active__c won't be relevant until after a User has been inserted.
hoomelhoomel

Guys, I am really questioning myself right now. But good that it was such an obvious thing I overlooked!

 

Thanks for the quick help!