function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AshwinAshwin 

main method in Apex class

Hi all,

 

I have a simple question but not able to figure out. I have a controller class and it has few methods. I wanted to know if its possible to add a main method as in Java? Or any other possibility to create a method which is always invoked when the page is loaded.

 

Thanks in advance

 

Ashwin

Best Answer chosen by Admin (Salesforce Developers) 
AshwinAshwin

Thanks. This will solve my problem. 

All Answers

JimRaeJimRae

Your controller class can have a constructor that would always get invoked when the class is instantiated.

 

 

public class MyController { private final Account account; //my constructor, executes first, as soon as the class is invoked public MyController() { account = [select id, name, site from Account where id = :ApexPages.currentPage().getParameters().get('id')]; } public Account getAccount() { return account; } public PageReference save() { update account; return null; } }

 

 

AshwinAshwin

Hi Jim

 

Thanks for your reply. I realized that a constructor could do the job. But the problem is the logic that need to run on page load will sit in the constructor plus I have to have an additional class to create the object. Will there be any apex tag that could call the method on page load?  Main method would have been ideal. My method actually invokes a webservice.

JimRaeJimRae

I didn't understand your requirement.

You can specify an action parameter on your page tag that executes a specific method in your controller.

This would occur on page load.


I think that might be what you are looking for.

 

 

<apex:page controller="mypageCON" action="{!main}" > </apex:page>

 

 

 

AshwinAshwin

Thanks. This will solve my problem. 

This was selected as the best answer