redirect to a page from apex in the constructor

  • I have a method in the page constructor that checks if a user has access to the page. If not, I want to redirect the user to another "Access Denied" page. I know I can use Pagereferences as part of a VF page and return to the page. But since I do my validation in the constructor, I cannot do that. Any solutions to resolve the issue?

    use action attribute to call pagereference method

    In addition to the answers, I'd like to mention something neither of them did: the action method on the `apex:page` element runs after the constructor but before the page is rendered, so the user won't see "part of an interface" or some such. They'll be cleanly redirected to the correct page if a PageReference is returned from the action method.

  • Himanshu

    Himanshu Correct answer

    6 years ago

    You can't redirect from constructor so you need to use the apex:page action attribute for that.

    <apex:page controller="YOURCONTROLLERNAME" action="{!YOURMETHODNAME}">

    Your Apex Method:

     public PageReference validateAndRedirect(){
          //Write your logic here and redirect
          PageReference retURL = new PageReference('REDIRECT URL');
          return retURL;

    Nice and simple... works great - before I was using javascript to redirect, but this is obviously much better, and allows me to have a relative url in Salesforce that redirects to an external site... Thanks!

    Note that your users may get an error when they try to view the page, ***Insufficient Privileges***. If so, got to `Setup` and search for `Visualforce Pages`. Then find your page, and click on `Security`, and ensure that "Standard User" is added to the users allowed to access that page, and hit `Save`. More details can be found here

License under CC-BY-SA with attribution

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