7

I have a visualforce component as below:

<apex:component controller="RecordDisplayController">
 <apex:attribute name="objectName" description="An Sobject" type="Sobject" required="false" assignTo="{!objectvar}"/>      
</apex:component>

RecordDisplayController:

public class RecordDisplayController {

public sObject objectvar{get;set;}

 public RecordDisplayController.RecordDisplayController(){
        system.debug('===========================>'+ objectvar); // it's null

    }
}

My Visualforce page has:

<apex:page standardController="Account">

<c:recorddisplay objectName="{!Account}" />

</apex:page>

How to get the Account which I have mentioned in my VF page into the my controller associated with VF component? I used:

public RecordDisplayController.RecordDisplayController(ApexPages.StandardController stdController) {
this.objectvar = stdController.getRecord();
}

But this did not work. I know I have to assign a value to objectvar before using it but where can I do that since I do not call any method in VF component or VF page.

2 Answers 2

7

Yes, the value is null in the constructor-- the value is set sometime afterwards. Usually, I do something like this:

public class RecordDisplayController {
    SObject theRecord;
    public void setObjectVar(SObject record) {
        theRecord = record;
    }
    public SObject getObjectVar() {
        return theRecord;
    }
}

You can do additional stuff in setObjectVar, like query additional fields or populate additional data. Since setters may be called more than once, you may need to "guard" against multiple sets:

public void setObjectVar(SObject record) {
    if(theRecord == null && record != null) {
        // Do stuff here
    }
}
8

The attribute in the component is evaluated after the component's controller constructor runs. Within the constructor it will be null because it simply hasn't been evaluated yet.

You can see it here in the SFDC docs about the order of execution for VF pages on step 2.

enter image description here

0

You must log in to answer this question.

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