I'm trying to figure out how to insert or display records into two custom objects from one visualforce page. My objects are unrelated.
Object A (Id, Name), Object B (Color, Location)
Thank you for your helps in advance.
I'm trying to figure out how to insert or display records into two custom objects from one visualforce page. My objects are unrelated.
Object A (Id, Name), Object B (Color, Location)
Thank you for your helps in advance.
your VF Page
<apex:page controller="myController">
<apex:pageblock>
<apex:pageblockButtons>
<apex:commandButton value="Save" action="{!saveObjects}"/>
<apex:pageblockButtons/>
<apex:pageblocksection>
<apex:inputfield value="{!myA__c.Name}"/>
<!-- add any other fields you want for this object -->
</apex:pageblocksection>
<apex:pageblocksection>
<apex:inputfield value="{!myB__C.Color__c}"/>
<apex:inputfield value="{!myB__C.Location__c}"/>
</apex:pageblocksection>
</apex:pageblock>
</apex:page>
Controller
public class myController{
public ObjectA__c myA {get;set;}
public ObjectB__c myB {get;set;}
public myController(){
myA = new ObjectA__c();
myB = new ObjectB__c();
}
public void saveObjects(){
insert myA;
myB.ObjectA__c = myA.Id;
insert myB;
}
}
Caky, you need to write a custom controller/controller extension to do this, using a standard controller will only allow you to work with one object type if they're not related.
A very basic extension might look like this:
public with sharing class MyExtension
{
ApexPages.StandardController sc;
public ObjectB__c objB {get; set;}
public MyExtension(ApexPages.StandardController sc)
{
this.sc = sc;
objB = new ObjectB__c();
}
public ApexPages.PageReference SaveBoth()
{
insert objB;
return sc.Save();
}
}
In your page you would reference the first object as normal, and also objB
, but instead of calling the regular Save()
action you then call your own custom action in the extension which will save both records:
<apex:page standardController="ObjectA__c" extensions="MyExtension">
<!-- snip -->
<apex:inputField value="{!ObjectA__c.Name}"/>
<apex:inputField value="{!objB.Name}"/>
<apex:commandButton action="{!SaveBoth}" value="Save"/>