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.

    Controller:

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

    Page:

    <apex:page controller="MyController" action="{!MyActionMethod}">
    
    <!-- rest of page -->
    
    </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:

    https://developer.salesforce.com/forums?id=906F0000000957bIAA

    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:

    http://bobbuzzard.blogspot.co.uk/2011/08/dml-during-initialisation.html

License under CC-BY-SA with attribution


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