6

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?

2
  • use <apex:page> action attribute to call pagereference method – Ratan Paul Nov 19 '15 at 13:54
  • 2
    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. – sfdcfox Nov 19 '15 at 14:07
16

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

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

Your Apex Method:

 public PageReference validateAndRedirect(){

      //Write your logic here and redirect
      PageReference retURL = new PageReference('REDIRECT URL');
      retURL.setRedirect(true);
      return retURL;

 }
2
  • 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! – Brad Parks Oct 13 '16 at 12:09
  • 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 – Brad Parks Oct 13 '16 at 12:26
3

use <apex:page> action attribute to call pagereference method

VF page.

<apex:page controller="myCtrl" action="{!pageReferenceMethod}">


</apex:page>

Class

public class myCtrl{

    public myCtrl()
    {

    }

    public PageReference pageReferenceMethod()
    {
          return new PageReference('/001');
     }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.