[SalesForce] How to display records of an object in vf page through Pageblocktable using controller

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

Best Answer

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.

Related Topic