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 Answers
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;
}
-
Note that your users may get an error when they try to view the page, Insufficient Privileges. If so, got to
Setup
and search forVisualforce Pages
. Then find your page, and click onSecurity
, and ensure that "Standard User" is added to the users allowed to access that page, and hitSave
. More details can be found here Commented Oct 13, 2016 at 12:26
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');
}
}
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.