Unable to bind Component attribute with controller

Vivek picture Vivek · Jul 19, 2012 · Viewed 10.8k times · Source

I am trying to develop a visualforce custom component which takes an attribute from a visual force page. I need to access that attribute in controller's Constructor so that i can brings some records from database and i need to display those records in the Component. But problem is that i am not getting Attribute value in Controller.

See the below code to understand the problem clearly..

Controller :

public with sharing class AdditionalQuestionController {
    public String CRFType {get;set;}
    public AdditionalQuestionController () {
        system.debug('CRFType : '+CRFType);
        List<AdditoinalQuestion__c> lstAddQues = [Select AddQues__c from AdditoinalQuestion__c wehre CRFType = :CRFType];
        system.debug('lstAddQue : '+lstAddQue);
    }
}

Component :

<apex:component controller="AdditionalQuestionController" allowDML="true">
    <apex:attribute name="CRFType" description="This is CRF Type."  type="String" required="true" assignTo="{!CRFType}" />
        <apex:repeat value="{!lstAddQue}" var="que">
            {!que}<br />
        </apex:repeat>
</apex:component>

VisualForce page :

 <apex:page >
    <c:AdditionalQuestionComponent CRFType="STE" />
</apex:page>

Thanks, Vivek

Answer

Matt Lacey picture Matt Lacey · Jul 19, 2012

I believe the issue here is that you're expecting the member variable to have a value inside the constructor — the snag is that the instance of the class is being constructed! It doesn't exist yet and so there is no way that a non-static member variable could be given a value prior.

Instead of doing the query in your constructor, specify your own getter for lstAddQue and do the query in there when you need the data. Of course, you may want to cache the value so that the query is not run every time, but from the looks of things that won't be relevant here.