Unable to bind Component attribute to controller

I am trying to develop a custom visualforce component that accepts an attribute from a visual strength page. I need to access this attribute in the Constructor controller so that I can fetch some records from the database, and I need to map these records to Component. But the problem is that I am not getting the Attribute value in the controller.

See the code below to clearly understand the problem.

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, Vivec

+4
source share
2 answers

Unfortunately, the methods for setting attributes in the VF component are called after the constructor has returned. Here's an alternative solution for your controller using the getter method to populate your list (which will be called after your CRFType member variable):

 public with sharing class AdditionalQuestionController { public String CRFType {set;} public AdditionalQuestionController () { system.debug('CRFType : '+CRFType); // this will be null in the constructor } public List<AdditoinalQuestion__c> getLstAddQue() { system.debug('CRFType : '+CRFType); // this will now be set List<AdditoinalQuestion__c> lstAddQues = [Select AddQues__c from AdditoinalQuestion__c wehre CRFType = :CRFType]; system.debug('lstAddQue : '+lstAddQue); return lstAddQue; } } 
+2
source

I believe that the problem is that you expect the member variable to have a value inside the constructor - this is that the class instance is being built! It does not exist yet, and therefore it is not possible for a non-static member variable to be assigned a value earlier.

Instead of executing the query in your constructor, specify your own getter for lstAddQue and run the query where you need the data. Of course, you may want to cache the value so that the request does not start every time, but from the appearance of things that will not matter here.

+4
source

All Articles