2

Guys please help me I stuck with one problem I have one vf page which has 4 diffrent tabs, now for each tab I have visualforce component. The visualforce component creates two diffrent objects. I want to use only one controller for VF page and save the record of vf component using that controller. How can I do this using one controller.

<apex:page controller="MyController">
 <apex:form>
    <c:Component1/> <!-- uses Object 1, so need to save object 1 record -->
    <c:Component2 /> <!-- uses Object 2, so need to save object 2 record -->
    <c:Component3 /> <!-- uses Object 2, so need to save object 2 record -->
    <c:Component4 /> <!-- uses Object 2, so need to save object 2 record -->

    <apex:commandButton action="{!SaveRecord}" value="Save" id="theButton"/>    
 </apex:form>
</apex:page>

Can I also save the record using VF component's save button?

3
  • It is not doable in straight forward way if you are not passing any attribute value in component. Here it looks like that each component has it own controller. – Ashwani Jan 22 '17 at 18:09
  • Sorry my bad, I am passing attribute values to my component – salesforce Developer Jan 22 '17 at 18:11
  • You should update your question with the attribute details also. However, I have given the approach in answer. – Ashwani Jan 22 '17 at 18:25
2

It should be doable in this way:-

Assuming you pass the attribute in component. So, those values should be passed from the VF controller:

public class MyController 
{
    public Object_1__c object1 {get;set;}
    public Object_2__c object2 {get;set;}
    public Object_3__c object3 {get;set;}
    public Object_4__c object4 {get;set;}

    public MyController()
    {
        // Initialize these objects or fetch by query
    }

    public void SaveRecord()
    {
        update new List<Sobject>{object1,object2,object3,object4};
    }
}

VF Page:

<apex:page controller="MyController">
 <apex:form>
    <c:Component1 objectInstance="{!object1}"/> <!-- uses Object 1, so need to save object 1 record -->
    <c:Component2 objectInstance="{!object2}"/> <!-- uses Object 2, so need to save object 2 record -->
    <c:Component3 objectInstance="{!object3}"/> <!-- uses Object 2, so need to save object 2 record -->
    <c:Component4 objectInstance="{!object4}"/> <!-- uses Object 2, so need to save object 2 record -->

    <apex:commandButton action="{!SaveRecord}" value="Save" id="theButton"/>    
 </apex:form>
</apex:page>

Whatever changes you will make in these components will automatically reflect in page controller.

If you are looking for more approaches, here is the code golf: Passing a list from VF component to VF page?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.