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
Srikanth DorepalliSrikanth Dorepalli 

how to add a custom object to another custom object (the related record) by setting Id field in salesforce when using dml

LOOK AT THIS ONE:-
Account acct = new Account(Name='SFDC Account');
insert acct;

// Once the account is inserted, the sObject will be 
// populated with an ID.
// Get this ID.
ID acctID = acct.ID;

// Add a contact to this account.
Contact mario = new Contact(
    FirstName='Mario',
    LastName='Ruiz',
    Phone='415.555.1212',
    AccountId=acctID);
insert mario;

MY QUESTION:-
----------------------------
If i want to append the ID like above snippet for custom objects how can i achieve this
 
Best Answer chosen by Srikanth Dorepalli
LBKLBK
Here is a sample code to showcase the relationship.

I have just derived it from the Account - Contact relationship you have shown above.
 
Parent_Object__c parentRecord = new Parent_Object__c(Name='SFDC Parent_Object__c');
insert parentRecord;

// Once the Parent_Object__c is inserted, the sObject will be 
// populated with an ID.
// Get this ID.
ID parentId = parentRecord.ID;

// Add a Child_Object__c to this Parent_Object__c.
Child_Object__c childRecord = new Child_Object__c(
    Name='childRecord',
    Parent__c=parentId);
insert childRecord;
Let me know if this helps.
 

All Answers

Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Srikanth,

May I request you to please check the below link for Creating Parent and Child Records in a Single Statement Using Foreign Keys. I hope it will be helpful.

BestRegards
RahulKumar
LBKLBK
Here is a sample code to showcase the relationship.

I have just derived it from the Account - Contact relationship you have shown above.
 
Parent_Object__c parentRecord = new Parent_Object__c(Name='SFDC Parent_Object__c');
insert parentRecord;

// Once the Parent_Object__c is inserted, the sObject will be 
// populated with an ID.
// Get this ID.
ID parentId = parentRecord.ID;

// Add a Child_Object__c to this Parent_Object__c.
Child_Object__c childRecord = new Child_Object__c(
    Name='childRecord',
    Parent__c=parentId);
insert childRecord;
Let me know if this helps.
 
This was selected as the best answer