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
dfalsodfalso 

Best way to automatically run controller methods at page instantiation?

Hi all, I'm pretty new to SalesForce development, so maybe this has been answered somewhere else and I missed it. If so, I apologize.
Anyway, I'm working with a custom object that has a one-to-many relationship with another custom object (in fact, I'll have a chain of about 5 when I'm done). I created a custom page and was confused when the detail object didn't inherit the master's Id. I found this link that (I think) is the same problem with a solution:
http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=5894

What I'm wondering now is the best way to run this class. FYI, I was initially planning on using a standard controller with this as an extension. Ideally, the class would run at page instantiation. I suppose I'd be okay with running it just before the save action. I'd ideally not do it as a trigger (this to me is an issue related to the custom page, not something that should happen globally - but maybe I'm wrong). Any recommendations? If I were to couple it to the save button, how would that go? Can an extension call a standard action (in which case I'd point the button at an extension method which would write the Id and then save)? If not, I think I need to write a custom controller, right?

Thanks for any assistance.
-Dominic
David VPDavid VP
A controller (or extension) is always 'run' or better 'instantiated' when your page is called : it will run it's 'constructor' when instantiated (the constructor is the method with the same name as the name of the class - it might or might not take arguments).

So whatever you want to run when your page is called, put it in your controller's constructor (or the constructor of your extension if that's what you're using).

Code:
public class MyCustomExtension {

     //constructor - (receives reference to stand. controller)
     public MyCustomExtension(ApexPages.StandardController stdController) {
        //put the code that you want to run when you page is called here
     }

}

 

If you instantiate a class yourself you do something like :
MyCustomClass mc = new MyCustomClass();

but a controller extension will be instantiated by the VF framework for you - and it will always receive a reference to the standardcontroller.


hope this helps,


David

dfalsodfalso
Perfect, yes, that's what I needed to know. I was afraid the class wouldn't be instantiated unless I actually used it on the page or something (and then would have to worry about making a hidden field, etc.).
Thanks for your help.


Message Edited by dfalso on 10-15-2008 01:59 PM