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

Button on Page Layout to do some work and then maybe or maybe not display a VF page.

I want to put a button on a VF Page that does the following--


  1. Runs some Apex code to create a new record via some backend processing.
  2. If successful, just transfer to the new record.
  3. If not successful, then display some error message. 

What I was thinking is that the button would ask for a VF page.  The constructor on the controller would do the work of creating the record.  If an error was detected, then the VF page would display the errors and the only button would be close.  If success, that's where I haven't figured it out yet.  I don't want to display a page here, I just want to go to the record.  I don't know if there's a way to do a redirect within the controller constructor.


Any ideas how to design this?



All you need to do is make sure that you capture the ID of the record that was inserted.


Then you redirect the user to  that ID.


          newPage = new PageReference('/' + ID);             
          return newPage.setRedirect(true);
 Hope that helps you out.



Can you do that in a Constructor?  A Constructor doesn't, by definition, doesn't return anything.




I seem to remember the correct way to transfer controller to another record is to instanciate the default controller for that record and then call the display method on it.  Maybe that's the correct strategy.



Yes this can be done.  


Check out the pagerefrence in the VisualForce guide.


The PageReference documentation just says how to do it from an action method.  I want to redirect from a constructor.


Could I just call an action method from the constructor and have that set the page reference and do the redirect?


You can bind the action to the action atttribute on the page component which is invoked before the page is returned offering a mechanism for conditional routing.

Can you explain that further or provide an example?



Okay, I think I got it.  Use the "action" attribute on the apex:page tag.  I will try that.


action The action method invoked when this page is requested by the server. Use expression language to reference an action method. For example, action="{!doAction}" references the doAction() method in the controller. If an action is not specified, the page loads as usual. If the action method returns null, the page simply refreshes. This method will be called before the page is rendered and allows you to optionally redirect the user to another page. This action should not be used for initialization.ApexPages.Action


Yep, that's it. Not much to it. :)