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
Nisar AhmedNisar Ahmed 

Creating child object records for a parent object.



I have two custom objects 'Contact__c' and 'Gift_Aid__c' where a Contact object can have multiple Gift Aid records.

A look up relation has been created from 'Gift_Aid__c' on 'Contact__c'.


I have  a VF page where I am using the fields of both the objects. When I save the page, a Contact and a Gift Aid record associated with the contact needs to be created.


Can anyone please provide me a sample controller code for the above scenario.


Any help regarding this will be highly appreciated.






Do u want to add the data to both objects from your VF page at a time?


Nisar AhmedNisar Ahmed

Yes. I want to add data to both the objects.

Shashikant SharmaShashikant Sharma

You jsut need to save the Conatct first and then Gift_Aid__c and use contact id in reference field 

public PagaReference saveRecords()

insert contactRecordInstance;

giftAidRecordInstance.Contact__c =;
insert giftAidRecordInstance;
return null;



your code should be like this


Ankit AroraAnkit Arora

Just insert contact record using :


insert contactObj;

Now use this contact id to fill contact in


giftAidObj.contact__c =;
insert giftAidObj;


record  record and then insert it.






Ankit Arora

Blog | Facebook | Blog Page

Nisar AhmedNisar Ahmed

Thanks for the reply.


I did the same thing and it works.

But now the problem is I want to add multiple child records 'Gift Aid' (say 3 to 4 records) associated with the parent record 'Contact' in a single VF page at the same time with different user input data.


Please let me know if you have any idea or work around to accomplish this.




Nisar Ahmed


When addressing this problem I have  found it easiest to created a seperate form on the vf page for the child object, then when you click the submit button, the object is not inserted but instead created and added to a list of the appropriate object. 

So, when you click the submit button for the page (the Contact) it inserts the contact as above, then iterates through the list of Gift Aid objects, adding the id and then inserting. 


If you want a visual representation for the user, it is also very easy to add the list to an apex:dataList and set it to rerender whenever another chiold object is added. This solution has worked very well for me, and prevents the need to use a multi-page wizard.


@zachumen Can you please share a sample code of the VF Page and Apex Class?