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
ekorzekorz 

apex create related records in one trigger

I'm hoping to create several records, and connect them through lookups, all at once.  I've used this chapter from the handbook in the past to create parent + children records at the same time, in classes & triggers.  http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_dml_foreign_keys.htm

As soon as I try to do the same thing, but with simple lookup relationships instead of parent+child relationships, the foreign key part seems to break.  So, quoting the handbook, this no longer seems to work:

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

I'm using custom objects so these lines looks more like:

Custom_Object__c placeholder = new Custom_Object__c (
            MyExtID__c='SAP111111');
newobject.Custom_Related_Object__c = placeholder;

I've tried
newobject.Custom_Related_Object__r = placeholder;
and it throws an error that my sobject can't be assigned to a list

I've tried
newobject.Custom_Related_Object__r.id = placeholder.id;
and it saves, but doesn't work

Anyone know how to handle this? 
Best Answer chosen by ekorz
hitesh90hitesh90
Hi ekorz,

Yes,
Here you have to Put insert statement before assign the id of the custom object record.
see below updated code.

Custom_Object__c placeholder = new Custom_Object__c (
            MyExtID__c='SAP111111');
  
insert  placeholder;
newobject.Custom_Related_Object__r.id = placeholder.id;

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator & Advanced Administrator & Sales cloud consultant
My Blog:- http://mrjavascript.blogspot.in/

All Answers

hitesh90hitesh90
Hi ekorz,

Yes,
Here you have to Put insert statement before assign the id of the custom object record.
see below updated code.

Custom_Object__c placeholder = new Custom_Object__c (
            MyExtID__c='SAP111111');
  
insert  placeholder;
newobject.Custom_Related_Object__r.id = placeholder.id;

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator & Advanced Administrator & Sales cloud consultant
My Blog:- http://mrjavascript.blogspot.in/
This was selected as the best answer
ekorzekorz
Oh man, that's it.  I'm totally overthinking it... I can just create these with seperate insert statements, I don't even need a foreign key record at all.  Long night!  Thank!