I need to save two objects that have parent child relationship , using a single visual force page. And also I need to pass values to the controller from the form both parent and child object's values. Is there any way to implement this?
1 Answer
It is not possible to define a VisualForce page with two entries in the standardController attribute. You can write an Apex class to handle this. It wouldn't have to be very complex.
As an example:
class ParentObjectExtension
{
public ApexPages.StandardController parentController {get;set;}
public ApexPages.StandardController childController {get;set;}
public Parent_Object__c ParentObject {get;set;}
public Child_Object__c ChildObject
{
get
{
if (ChildObject ==null)
{
ChildObject = new Child_Object__c();
}
return ChildObject;
}
set;
}
public ParentObjectExtension (ApexPages.StandardController ctrl)
{
parentController = ctrl;
childController = new ApexPages.StandardController (ChildObject);
}
public PageReference SaveBoth()
{
PageReference pr = parentController.Save();
if (pr != null)
{
ChildObject.Parent__c = ParentObject.Id;
if (childController.Save() == null) pr = null;
}
return pr;
}
}
If you VF has Parent_Object__c as the standardController and this class as an extension, you can reference fields from both Parent_Object__c (as {!Parent_Object__c.Field_Name__c} ) and Child_Object__c ( as {!ChildObject.Field_Name__c} )
And your save button needs to call the SaveBoth method not the standard Save.
This only works for brand new objects. You could use it to edit an existing Parent/Child if you modify the ChildObject getter to find the existing child based on the parent's Id.
NB I just typed this in here and haven't syntax checked or compiled, so I expect typos etc. It's really just to start you off.