Activity › Forums › Salesforce® Discussions › How to create a child record from parent when external id is updated on parent record in Salesforce?
Tagged: Child Record, External ID, Objects, Parent Record, Salesforce Contacts
-
How to create a child record from parent when external id is updated on parent record in Salesforce?
Posted by Deepak on November 21, 2019 at 2:36 PMHow to create a child record from parent when external id is updated on parent record?
Yogesh replied 6 years, 5 months ago 3 Members · 2 Replies -
2 Replies
-
- [adinserter block='9']
-
Hello,
try this code below , hope it will help you :-
public static void syncInsuranceBuyers( List<BuyerWrapper> lstBuyers ) {
List<Account> lstBuyers = new List<Account>();
List<Contact> lstMembers = new List<Contact>();// Iterate over all the buyers to create a list for upserting the records
for( BuyerWrapper bw : lstBuyers ) {// Create a new instance of Account sObject and add it into the list
lstBuyers.add(
new Account(
Name = bw.name,
ERP_Id__c = bw.IdFromExternalSystem
// You can add addional fields mapping here
)
);// Iterate over the related members
for( MemberWrapper mw : bw.members ) {
// Create a new instance of Contact sObject and add it into the list
lstMembers.add(
new Contact(
FirstName = mw.firstName,
LastName = mw.lastName,
ERP_Id__c = mw.IdFromExternalSystem,
Account = new Account( ERP_Id__c = bw.IdFromExternalSystem )
// You can add addional fields mapping here
)
);
}
}// Will have to make 2 different DML calls as we need to specify the ExternID field
// which will be used to identify the existing records and will update themDatabase.UpsertResult[] resultsAcc = Database.upsert( lstBuyers, Account.Fields.ERP_Id__c );
Database.UpsertResult[] resultsCon = Database.upsert( lstMembers, Contact.Fields.ERP_Id__c );/****
* If it was just an insert opertaion then it could be achieved in a single DML
*
List<sObject> lstAllRecords = new List<sObject>();
lstAllRecords.addAll( lstBuyers );
lstAllRecords.addAll( lstMembers );
Database.SaveResult[] results = Database.insert( lstAllRecords );* Since, upsert DML operation requires an external ID field defination as an extra parameter and we have 2 different fields so above can’t be
* achieved in a single DML call.
***/
}
Log In to reply.