+ Start a Discussion
DaveHDaveH 

Redirecting to another page in Visualforce without using "setRedirect(true)"

Hey everybody,

 

I figured I would share a little trick that I used to get over a seemingly common and un answered question. I needed to have a Visualforce page that would redirect the user to a second VF page based on information passed in the URL query string. The tricky part here is that I caould not use the setRedirect() method because I needed to maintain the state of all variables in the controller. So, using a little javascript (very little) I was able to redirect the user to a page AND maintain the state of the controller object at the same time. See the code below:

 

Redirect Page:

 

<apex:page controller="PortalChangePreferencesController" showHeader="false" sidebar="false" id="thisPage">
<apex:form >
  <h1>Redirecting....</h1>
  <apex:commandButton action="{!redirectToPrefsPage}" rendered="true" id="button1" rendered="false"/>
  
  <script>
      var button = document.getElementById("{!$Component.button1}");
  </script>
  
</apex:form>

    <script>
      window.onload = new function() { button.click(); }
  </script>
</apex:page>

 Notice the commandButton calls a method in the controller that contains the redirect logic. The button IS NOT rendered. Next, the first bit of JScript initializes a variable that we will use to automatically click the button. The next step is to click the button when the page is loaded so I hooked a function onto the window.onload event and there you go! Now, when the page is loaded, the button will be automatically clicked and the method in the controller will redirect the user. I put the code for the controller below. Enjoy!

 

Controller:

 

public class PortalChangePreferencesController {

	public Subscription__c subscription { get; set; }
	private boolean redirect = true;
	
	public PortalChangePreferencesController() {
		String subId = ApexPages.CurrentPage().getParameters().get('subId');
		System.debug('SUB ID = ' + subId);
		
		if(subId != null && !subId.trim().equals(''))
		{
			Subscription__c result = [select Id, Email__c 
										from Subscription__c 
										where Id = :subId limit 1];
			
			if(result == null)
			{
				redirect = false;
			}
			else
			{
				this.subscription = result; 
			}
		}
		else
		{
			redirect = false;
		}
	}
	
	public PageReference redirectToPrefsPage() {
		if(redirect)
		{
			return Page.PrefLoginPage;
		}
		else return Page.Unauthorized;
	}
}

 NOTE: I apolgize if this question has been recently answered somewhere on the forums but if it was I am unable to find it so I figured I would post my solution.