Order of Invocation – Controller Methods (Constructor, Getter, Action Method)

I was browsing through Visual Force Dev cookbook and was trying to understand the sequence of execution of the controller methods ( constructor, getter, action method) while invoking the action method via the actionpoller.

Basically would like to know the below:
[1] When is the Constructor called; is it when the VF connected with the controlled is rendered everytime?
[2] When is Getter and Action methods called? What should be the sequence in this example?

I tried to get some debug dumps which suggests the sequence as ** Constructor -> Getter -> Action Method ** which is confusing as Action Method is call first as you could see in the snippet below.

public with sharing class PollerController{
    public List<String> states=new List<String>{'Connecting to Bank', 'Authorised', 'Complete'};
    private Integer stateIdx=0;
    public String getPaymentState()
    { return states[stateIdx];}
    public PageReference movePayment() 
    {
        stateIdx++;
        return null;
    }
}

public with sharing class PollerController 
{
    Public PollerController(){
        system.debug('** Inside Constructor **'); }
    public List<String> states=new List<String>{
      'Connecting to Bank', 'Authorising',  'Authorised', 'Complete'};
    private Integer stateIdx=0;
    public String getPaymentState()
    {
       system.debug('** Inside getPaymentState Method **');
       return states[stateIdx];
    }
    public PageReference movePayment() 
    {
        system.debug('** Inside Action Method **');
        stateIdx++;
        return null;
    }
}

Answer

You can find full details of the order of execution for Visualforce pages at:

http://www.salesforce.com/us/developer/docs/pages/index_Left.htm#CSHID=pages_controller_lifecycle.htm|StartTopic=Content%2Fpages_controller_lifecycle.htm|SkinName=webhelp

Some things are unexpected, in that getters can execute more than once when the page is being rendered – presumably this is because it can take multiple passes with a single page to generate the output.

Be wary of trying to infer the ordering, as the underlying code may change without warning and alter the order. Only trust the docs!

Attribution
Source : Link , Question Author : sHiBuKaLiDhAsAn , Answer Author : Bob Buzzard

Leave a Comment