Tuesday, March 7, 2017

Single statement insert of parent and child custom objects

An example for inserting parent-child records in a single statement is provided by Salesforce here.


The crux of it is to create a parent reference record and refer to it in the child record lookup instead of trying to refer to the parent record variable to be inserted, i.e.

Account accountReference = new Account(MyExtID__c='SAP111111');newOpportunity.Account = accountReference;

Account parentAccount = new Account(Name='Hallie', MyExtID__c='SAP111111');

Database.insert(new SObject[] { parentAccount, newOpportunity });


A couple of things I took some time to figure out were:

1. How to get this working with custom objects? e.g. if I have Parent__c and Child__c objects that are linked via custom field Child__c.Parent_Lookup__c

The equivalent of newOpportunity.Account in the example above would be Child__c.Parent_Lookup__r

I had an hour of brain fade wondering why Child__c.Parent_Lookup__c wouldn't work, but that would be the equivalent of newOpportunity.AccountId, not newOpportunity.Account.

2. I needed to do this bulkified.

I expect there is a syntax you could use to create an inline sobject list out of two non-sobject lists and insert in one line of code but I didn't invest the effort to get there and went with the following instead (heavily abridged pseudocode):

List<SObject> sobjList = new List();
for(loop criteria){
  Parent__c parentRec = new Parent__c(field values);
  sobjList.add(parentRec);
  Child__c childRec = new Parent__c(field values);
  sobjList.add(childRec);
}
Database.insert(sobjList);