This course is currently a work in progress. Please join the waitlist to receive regular updates.
Insert parent & child records in apex
As a salesforce developer, it’s common to set up records across multiple objects to meet business needs. For example, when onboarding a new customer, you would typically create both an Account and a Contact.
In Salesforce, you can establish a parent-child relationship using either a master-detail or lookup relationship.
To set up these relationships correctly:
- Insert the parent record first.
- Create a new instance of the child record and assign the parent record id to the master-detail or lookup field.
- Insert the child record.
Parent & Childs
Add a new child records to a parent
Following is an example of how to create an Account (parent) and a Contact (child) using a lookup relationship in Salesforce.
Loading...
In the above example:
- The variable
accRecord
is used to create an instance of account object. - The DML
insert
statement is used to add the account record. Once the operation is successful, salesforce generates a unique record id for the account. - The variable
contactRec
creates an instance of the contact object, and theAccountId
lookup field is populated with account's record id. - Once the DML operation is completed, the contact will display as the child of the account record.
Try It Yourself
Loading...