+ Start a Discussion
Abhilash DaslalAbhilash Daslal 

Assigning record ids to lookup fields on junction object

Hi,
I have the following code

Opportunity oppty = new Opportunity();
oppty.Name='123';
insert oppty;

Product2 pr = new Product2();
pr.Name = '123';
pr.Description = 'my product';

myJunctionObject obj = new myJunctionObject();
obj.Product2.id  = pr.id; //
obj.Opportunity.id  = oppty.id;
insert obj;

I am getting the error - Attempt to dereference a null object.Null pointer exception at 'insert obj;'
Can anyone suggest a solution to overcome this

Thanks,
Abhilash
Best Answer chosen by Abhilash Daslal
Om PrakashOm Prakash
Hi Abhilash,
You are using obj.Product2.id, you need to use obj.Product2Id as per bellow code.
(Same for obj.Opportunity.id , it should be obj.OpppurtunityId)
myJunctionObject obj = new myJunctionObject();
obj.Product2Id  = pr.id;
obj.OpportunityId  = oppty.id;
insert obj;
Additionally you missed insert statement for Product2 in your code.

All Answers

SFDC RohitSFDC Rohit
Update Code below:- 

Opportunity oppty = new Opportunity();
oppty.Name='123';
insert oppty;

Product2 pr = new Product2();
pr.Name = '123';
pr.Description = 'my product';
insert pr;

myJunctionObject obj = new myJunctionObject();
obj.Product2.id  = pr.id; //
obj.Opportunity.id  = oppty.id;
insert obj;

Thanks,
Rohit Jain
Om PrakashOm Prakash
Hi Abhilash,
You are using obj.Product2.id, you need to use obj.Product2Id as per bellow code.
(Same for obj.Opportunity.id , it should be obj.OpppurtunityId)
myJunctionObject obj = new myJunctionObject();
obj.Product2Id  = pr.id;
obj.OpportunityId  = oppty.id;
insert obj;
Additionally you missed insert statement for Product2 in your code.
This was selected as the best answer
mukesh guptamukesh gupta
Hi Abhilash,

Ignore above code, Please check tested code:-
 
Opportunity oppty = new Opportunity();
oppty.Name='123';
insert oppty;

Product2 pr = new Product2();
pr.Name = '123';
pr.Description = 'my product';
insert pr;

OpportunityLineItem obj = new OpportunityLineItem();
obj.Product2Id  = pr.id; 
obj.OpportunityId = oppty.id;
insert obj;

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh