1

I want to display records of an object in visual force page through Pageblocktable using controller which contains a method and method contains a query whcih retrive records in object? Note: where i should not use constructor Controller:

public class Redirect_Main {

    public List<Account> accs {set;get;}

    public void access(){
        accs = [select id,name,Industry from account];

    }
}

Visualforce page:

<apex:page controller="Redirect_Main">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accs}" var="a">
                <apex:column value="{!a.id}"/>
                <apex:column value="{!a.Name}"/>
                <apex:column value="{!a.Industry}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>    

While i am trying to retrieve records from object showing null page as a result.

please help me in this

Thanking you

KS Kumaar

2
  • 1
    Add action attribute to your page which calls the access() method or place that query in the constructor. Ex: <apex:page controller="Redirect_Main" action="{!access}"> – Krishna Bidwai Jul 25 '16 at 6:23
  • Please mark this as useful comment, If this helped you. – Krishna Bidwai Jul 25 '16 at 11:16
1

While you cannot do DML (Data Modification Language) in the constructor you can certainly query in the constructor:

public class Redirect_Main {

    public List<Account> accs {set;get;}

    public Redirect_Main(){
        accs = [select id,name,Industry from account limit 1000];
    }
}

This follows the idea that a constructor "prepares the new object for use".

Another common pattern is to "lazy load" properties so the query happens the first time the Visualforce references the property:

public class Redirect_Main {

    public List<Account> accs {
        get {
            if (accs == null) accs = [select id,name,Industry from account limit 1000];
            return accs;
        }
        set;
    }
}

Making use of the apex:page action attribute is probably best reserved for special cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.