[SalesForce] How do i pass data from visualforce page to component’s custom controller

I have a modal in the visualforce page that i want to move to its own component, for the most part its just displaying information. The data passed to the conponent controller constructor doesn't seem to be available. Here is a sample of how the code is setup.

main.page

<apex:page controller="mainCtrl">
<div class="modal fade"  id="myModal" tabindex="-1" role="dialog">
    <customCmp value="{!value}" >
</div> 
</apex:page>

customCmp.component

<apex:component controller="compCtrl">
    <apex:attribute type="String" name="value" assignTo="{!value}" description=""/>
</apex:component>

compCtrl.cls

class compCtrl {
   public String value {get; set;}
   compCtrl (){
      System.debug(value);
   }
}

Best Answer

Your controller's constructor is called before assignTo. It will be available by the time your component is rendered. Note that you should not have the attribute name and the assignTo value be the same name (this actually should cause a compilation error).

You can visually see this is working in the following code:

<apex:component controller="compCtrl">
  <apex:attribute name="value" assignTo="{!internalValue}" description="" />
  {!internalValue}
</apex:component>

....

public String internalValue { get; set; }
Related Topic