call apex method from visual force page (not in constructor)

  • I want to call public apex method on load of visual force page, for purpose of Excel exporting.

    But I don't want to put that method in Constructor of apex class, because of some limitation (example:I need to query all the records and leading to too many soql exception).

    Basically Visual Force page has some criteria, so I want to call this after setting criteria. Run the report and export as Excel.

    How can take approach for calling certain apex method from on load of Visual force page.

  • Bob Buzzard

    Bob Buzzard Correct answer

    8 years ago

    You can use the action attribute of the page tag for this - that will execute an action method on the controller before anything is rendered. E.g.


    public class MyController
       public void MyActionMethod()
          // do some stuff here


    <apex:page controller="MyController" action="{!MyActionMethod}">
    <!-- rest of page -->

    One important point to note - this should not be used to initialise information that other parts of the page rely on, as there is no guarantee that this method will be called before the getters (my understanding is that is how it currently works, but may change in the future) - there's a thread with one of the Visualforce developer's explaining this in more detail at:

    If this causes a problem, the other way is to execute some JavaScript when the page loads that invokes the action method and then renders the rest of the page. I've blogged that solution at:

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM