+ Start a Discussion
Rahul Singh Rana 9Rahul Singh Rana 9 

how to insert record and relate it to existing record

Hi,

Have a question, please help.


I am trying to insert a record and relate it to existing record. For example, if we want to insert a contact relating to existing Account, then we would write as follows:

Contact con = new Contact(LastName = 'Rahul');
con.AccountID = //here account ID will go
insert con;

My first question is, why the below code does not work(that is, it relates contact and Account, but does not show the same on UI, Account field is blank on Contact)

Contact con = new Contact(LastName = 'Rahul);
con.Account = //Account Object reference here.
insert con;

My second question is: lets say we have two custom objects Job Application and position, in which position is master object. Then how do we insert Job application object related to existing position. below code does not work for me:


Job_Application__c job = new Job_Application()
job.position__r = //position object reference here.
insert job;

this code does create job applicaton object but does not relate it to position object.

PLEASE HELP


best Reagrds,

Rahul SIngh Rana
Best Answer chosen by Rahul Singh Rana 9
LBKLBK
Hi Rahul,

My first question is, why the below code does not work(that is, it relates contact and Account, but does not show the same on UI, Account field is blank on Contact)

Contact con = new Contact(LastName = 'Rahul);
con.Account = //Account Object reference here.
insert con;

LBK: Lookup reference internally carries only the ID of the referenced record. So, it has to be con.Account = objAccount.ID, where objAccount is your Account record.

My second question is: lets say we have two custom objects Job Application and position, in which position is master object. Then how do we insert Job application object related to existing position. below code does not work for me:


Job_Application__c job = new Job_Application()
job.position__r = //position object reference here.
insert job;

LBK: __r is the way to access the fields of the parent record. For example, job.position__r.Id, job.position__r.Name, etc. To set the position__c field in job record, you need to use job.position__c = objPosition.Id, where objPosition is your position record.

Hope this helps.