2

Is there a way to pass values from a controller in a VF page down to a child component?

I need a way to do the following:

My page:

 <apex:page controller="myCustomController">

      <c:myComponent>


      </c:myComponent>

 </apex:page>

My component:

 <apex:component>

       <input value="{!myObj.value}" />

 </apex:component>

Where "myObj" is a custom object in myCustomController

The problem is myComponent isn't able to read the values from myCustomController. Is there a way to do this without assigning the controller to the component as well? I ask because the page we're building uses multiple components that need to all reference that singular controller, and making them all one page is not an option.(We're using about ten custom components that display dynamically, but we don't want ten instances of the controller running if it can be avoided)

Thanks!

1 Answer 1

3

You can pass the controller itself in to the component.

Controller

public class myCustomController {
  public myCustomController getSelf() {
    return this;
  }
}

Component

<apex:component>
  <apex:attribute name="pageController" type="myCustomController" description="The page's controller" />
</apex:component>

Page

<apex:page controller="myCustomController">
  <c:myCustomComponent pageController="{!self}" />
</apex:page>

Or, as an alternative, you could always build the state in to a separate class as well. When you use this technique, even if there are multiple instances of components that accept the same controller, they can all share the data with each other and the page itself.

Note that only one "copy" of the controller will be present in this scenario, since they will all reference the same object. You can access all public variables and methods that are present in the controller.

2
  • I gave this a try, and it won't let me deploy. My component is giving the error "[ApexComponent] Unknown property 'myObj'" Should the getSelf be separate from the actual public myController() or inside of it? I currently have it laid out as such: public with sharing class myController{ public myController getSelf(){ return this; } public myController{ (methods) } Commented Mar 26, 2019 at 20:32
  • @ChristopherCarlson The markup in the component will need to reference the attribute. e.g. <input value="{!myObj.value}" /> would change to <input value="{!pageController.myObj.value}" />. Alternatively, you can write a custom controller for the component too, in order to shorten the amount of markup you need to write.
    – sfdcfox
    Commented Mar 26, 2019 at 20:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .