[SalesForce] Visualforce page redirect on page load

When my Visualforce page loads, I have a record loaded with a field that is a checkbox. If the checkbox is checked (is true), I want to redirect to another Visualforce page. I currently have an init() function in my constructor of my controller for the Visualforce page. When I've added like logic it doesn't redirect. Look for the code comment "this line here". I'm not sure why it's not redirecting.

public class TakeSurveyController
{
  private String headerId = ApexPages.currentpage().getParameters().get('header');  
  private String surveySentId = ApexPages.currentpage().getParameters().get('id');
  private String isPreview = ApexPages.currentpage().getParameters().get('ispre');
  private Map<Id, SEO__CSEO_Survey_Question__c> questionmap = new Map<Id, SEO__CSEO_Survey_Question__c>();

  public SEO__CSEO_Survey__c NewSurvey { get; set; }
  public Id surveyId { get; set; }
  public Id cntid { get; set; }
  public Id souceid { get; set;}
  public List<SEO__CSEO_Survey_Question__c> SurveyQuestions { get; set; }
  public List<SEO__CSEO_Referral_Site__c> SurveySites { get; set; }
  public SEO__CSEO_Survey_Response_Header__c SurveyHeader { get; set; }
  public SEO__CSEO_Survey_Response_Header__c InsertSurveyHeader { get; set; }

  public String surveyScoreStr { get; set; }

  public TakeSurveyController()
  {
      init();

  }    

  // redirects to desired page. works when user clicks a button
  // on the vf page
  public PageReference giveFeedback()
  {
      PageReference retPage = new PageReference('/apex/CompleteSurvey');
      if(surveySentId != null && surveySentId != '')
      {
          retPage.getParameters().put('id', surveySentId);
      }
      /*
      if(isPreview != null && isPreview != '')
      {
          retPage.getParameters().put('ispre', isPreview);
      }

      if(cntid != null && cntid != '')
      {
          retPage.getParameters().put('cntid', cntid);
      }
      if(souceid != null && souceid != '')
      {
          retPage.getParameters().put('souceid', souceid);
      }
      */
      retPage.setRedirect(true);
      return retPage;
  }


  private void init()
  {

    SEO__Survey_Sent__c sent = [SELECT SEO__Survey__c, SEO__Contact__c
                                FROM SEO__Survey_Sent__c
                                WHERE Id = :surveySentId
                               ];

      surveyId = sent.SEO__Survey__c;
      cntid    = sent.SEO__Contact__c;
      souceid  = sent.SEO__Contact__c;

      SurveyHeader = new SEO__CSEO_Survey_Response_Header__c();
      NewSurvey = [select Id, name, SEO__Background_Image__c, Question_1_Threshold__c, SEO__Display_Welcome_Page__c, Survey_Type__c, Survey_Status__c, SEO__No_Testimonial_Thank_You__c, SEO__Survey_Welcome_Heading__c, SEO__Testimonial_Request__c, SEO__Testimonial_Thank_You__c, SEO__Welcome_Text__c from SEO__CSEO_Survey__c where Id =:sent.SEO__Survey__c];
      SurveyQuestions = [select Id, Name, SEO__Low_Rating__c, SEO__High_Rating__c, SEO__CSEO_Survey__c, SEO__Order__c, SEO__Question__c, SEO__Status__c from  SEO__CSEO_Survey_Question__c where SEO__CSEO_Survey__c = :sent.SEO__Survey__c and SEO__Status__c = 'Active' order by SEO__Order__c];
      for(SEO__CSEO_Survey_Question__c ques : SurveyQuestions)
      {
          questionmap.put(ques.Id, ques);
      }
      SurveySites = [select Id, name, SEO__Site_Name__c, Site_URL__c from SEO__CSEO_Referral_Site__c where SEO__CSEO_Survey__c = :sent.SEO__Survey__c];              
      InsertSurveyHeader = new SEO__CSEO_Survey_Response_Header__c();
      if(headerid != null && headerid != '')
      {
          InsertSurveyHeader = [select Id, Name, SEO__Testimonial__c, SEO__Testimonial_Given__c from SEO__CSEO_Survey_Response_Header__c where Id = :headerId];


      }

      // this line here
      if([select SEO__Display_Welcome_Page__c from SEO__CSEO_Survey__c where Id =:sent.SEO__Survey__c].SEO__Display_Welcome_Page__c) {
        giveFeedback();
      }        



  }
}

Visualforce Page

<apex:page showHeader="false" standardStylesheets="false" title="Survey" controller="TakeSurveyController" cache="false">
    <html lang="en">
    <script>
        const images = "{!URLFOR($Resource.img, 'uploads/')}";
        var h = document.getElementsByTagName("html")[0];
        var b = document.getElementsByTagName("body")[0];
        h.style.backgroundImage = `url(${images}{!NewSurvey.SEO__Background_Image__c})`;
        b.style.backgroundImage = `url(${images}{!NewSurvey.SEO__Background_Image__c})`;
        console.log(`{!NewSurvey.SEO__Background_Image__c}`);
        console.log(`{!NewSurvey.SEO__Welcome_Text__c}`);        

    </script>  
    <head>
        <meta charset="utf-8"/>
            <meta http-equiv="X-UA-Compatible" content="IE=edge"/ >
            <meta name="viewport" content="width=device-width, initial-scale=1"/>
            <meta name="description" content=""/>
            <meta name="author" content=""/>

            <title>Survey</title>

            <!-- Bootstrap -->
            <link href="{!URLFOR($Resource.AppResource, './assets/bs/css/bootstrap.min.css')}" rel="stylesheet"/>
            <!-- FontAwesome CSS -->
            <link rel="stylesheet" href="{!URLFOR($Resource.AppResource, './assets/fa/css/font-awesome.min.css')}"/>
            <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
            <link href="{!URLFOR($Resource.AppResource, './assets/css/ie10-viewport-bug-workaround.css')}" rel="stylesheet"/>

            <!-- Custom -->
            <link href="{!URLFOR($Resource.AppResource, './assets/css/cover.css')}" rel="stylesheet"/>

            <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
            <!--[if lt IE 9]>
              <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
              <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
            <![endif]-->

    </head>



    <body class="wcs">
        <apex:form >
            <apex:actionFunction name="givefeedback" action="{!giveFeedback}"/>
        </apex:form>
        <div class="site-wrapper">
          <div class="site-wrapper-inner">
            <div class="cover-container">

              <div class="inner cover">
                <div class="logo"><img src="{!URLFOR($Resource.AppResource, './assets/img/handshake-icon.png')}"/></div>
                <h1 class="cover-heading">{!NewSurvey.SEO__Survey_Welcome_Heading__c}</h1>
                <p class="lead">{!NewSurvey.SEO__Welcome_Text__c}</p>
                <p class="lead">
                  <a href="javascript:void(0)" onclick="givefeedback()" class="btn btn-lg btn-orange">Give Feedback</a>
                </p>
              </div>

              <div class="mastfoot">
                <div class="inner">
                  <p>&copy; Touchpoint Solutions</p>
                </div>
              </div>

            </div>
          </div>
        </div>

        <!-- Bootstrap core JavaScript
        ================================================== -->
        <!-- Placed at the end of the document so the pages load faster -->
        <script src="{!URLFOR($Resource.AppResource, './assets/js/jquery.min.js')}"></script>
            <script src="{!URLFOR($Resource.AppResource, './assets/bs/js/bootstrap.min.js')}"></script>
        <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
        <script src="{!URLFOR($Resource.AppResource, './assets/js/ie10-viewport-bug-workaround.js')}"></script>      
    </body>    
</html>
</apex:page>

Best Answer

You have a couple problems:

  1. Your method is void.
  2. You do not add any action attribute to your page tag.

First you have to change your controller to return the proper type:

public PageReference init()
{
    // other code

    if (someCondition)
        return someRedirect;
    return null;
}

Then you have to change your markup to specify an action attribute on your <apex:page> tag:

<apex:page ... action="{!init}">
Related Topic