+ Start a Discussion
davidwatdavidwat 

How to get the Id of the last inserted record to make a lookup relationship with another record?

Hi all,

I have recently faced a problem while creating an apex class for inserting two records from a visulaforce page. I want to insert the contact info in contact object and then want to get the Id of that contact  record to assign it to ContactId in the Campaignmember object. But got error that the Id is null. Here is my code goes

 

Creating contact object:

----------------------------------------

Contact cont= new conatct();

cont.LastName=lastname;

...

...

insert cont;

That  works fine and the contact is being inserted

--------------------------------------------

Now  when I want to get the Id of the above record it given me an error

CampaignMember CaMem = new CampaignMember();

CaMem.ContactId  =cont.Id;

 

insert  CaMem;   // Error: the conatctId is null.

 

It means that the cont.Id is null. One way is to query the contact records and order them by a fields like creadteddate etc and get the last or first record and suppose that it is the one inserted just recently. I am not going with this solution.

 

Does anyone know how to solve this issue? Is there some system method that keep the id with its insertion inline to use it down in the code?

 

Any usefull suggestions please. Thanks for your support and help

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
CaptainObviousCaptainObvious

Are you sure the error is saying the ContactId is null? Perhaps you are missing the CampaignId instead?

All Answers

CaptainObviousCaptainObvious

Are you sure the error is saying the ContactId is null? Perhaps you are missing the CampaignId instead?

This was selected as the best answer
Siddharth Birari.ax1164Siddharth Birari.ax1164

When you are creating a record through Apex, you won't be able to access its Id, unless you query it...