+ Start a Discussion
Patricia LimPatricia Lim 

Save new records for two objects in a single VF page

I am in the process of developing an apex:form that will save two records: Recipient__c and Scholarship_Award__c. 

I need to create a custom controller to save new records for both objects on the same VF page. 
The trouble is the Recipient__c record will need to be saved first following the insertion of Scholarship_Award__c because it references Recipient__c as the parent in a master-detail relationship. 

Ideally, the end-user will input the fields of recipient__c, and scholarship_award__c and two records will be saved: a new recipient, and a new scholarship with that recipient as the parent. 

How can I go about developing this?
Best Answer chosen by Patricia Lim
Santosh Kumar 348Santosh Kumar 348
Hi Patrica,

There are multiple ways but the simplest one is inserting one after the other. For example you want to insert Account and Contact:
 
Account acc=new Account(Name='Blog Acc1');
insert acc;
 
Contact cont=new Contact(FirstName='Bob', LastName='Buzzard', AccountId=acc.id);
insert cont;

You can refer: http://bobbuzzard.blogspot.in/2012/03/create-parent-and-child-records-in-one.html

And if you want to insert it with single DML operation then follow below link:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm

If it helped then can you please mark it as the best answer so that it can be used by others in the future.

Regards,
Santosh Kumar