+ Start a Discussion
Jerry ClifftJerry Clifft 

This should be an easy one to answer, inserting new record to Objec B when A is inserted

I have two custom objects, Equipment and Equipment History. I would like to insert a new record into Equipment History when a record is inserted into Equipment. So far, I getting this error:

 

Apex trigger insertrecords caused an unexpected exception, contact your administrator: insertrecords: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.insertrecords: line 8, column 1

 

Here is my trigger:

trigger insertrecords on Equipment__c (after insert)
{
 Equipment__c[] eq = [SELECT Name from Equipment__c where id =: trigger.new];
 List<Equipment_History__c> copyeq;
 for(Equipment__c neweq : eq)
 
 {
  copyeq.add(new Equipment_History__c (Name=neweq.Name));
 }
 
 insert copyeq;
}
Best Answer chosen by Admin (Salesforce Developers) 
zachbarkleyzachbarkley

Hi Jerry,

 

Your absolutely right :-)  This one still gets me sometimes! copyeq is null until you make it an empty list to add items to

 

    trigger insertrecords on Equipment__c (after insert){
		 Equipment__c[] eq = [SELECT Name from Equipment__c where id =: trigger.new];
		 List<Equipment_History__c> copyeq = new List<Equipment_History__c> {};
		 for(Equipment__c neweq : eq){
		 	copyeq.add(new Equipment_History__c (Name=neweq.Name));
		 }
		 insert copyeq;
	}

 

Remember to use handler apex classes and not put requirements directly in trigger classes :-)

All Answers

zachbarkleyzachbarkley

Hi Jerry,

 

Your absolutely right :-)  This one still gets me sometimes! copyeq is null until you make it an empty list to add items to

 

    trigger insertrecords on Equipment__c (after insert){
		 Equipment__c[] eq = [SELECT Name from Equipment__c where id =: trigger.new];
		 List<Equipment_History__c> copyeq = new List<Equipment_History__c> {};
		 for(Equipment__c neweq : eq){
		 	copyeq.add(new Equipment_History__c (Name=neweq.Name));
		 }
		 insert copyeq;
	}

 

Remember to use handler apex classes and not put requirements directly in trigger classes :-)

This was selected as the best answer
Jerry ClifftJerry Clifft

Woot, that is EXACTLY what I was missing, thanks for the accurate and quick reply!

jungleeejungleee

Just a suggestion, Actually you wouldn't need to query the equipment__c object at all. You can direclty use the trigger.new context variable in the trigger, this will save you a query.

 

for(Equipment__c neweq : trigger.new){
   copyeq.add(new Equipment_History__c (Name=neweq.Name));
}

 Hope it helps!