VF controller redirect to another page

  • I have a Apex Controller for a VF page. I want to redirect my page to another one, only if I cannot get a specific parameter from the URL. current page: /apex/demo?param=123 -> stay on this page. current page: /apex/demo -> redirect to /apex/demo2.

    My controller's constructor:

    public demoController(){
    String p = ApexPages.currentPage().getParameters().get('param');
    if(p == null){
    // redirect to /apex/demo2
    }
    }
    

    How can I get it done? Thanks!

  • I figured out that I can use apex:page action="". VF:

    <apex:page controller="demoController" action="{!redirect}"/>
    

    Controller:

    public PageReference redirect(){
            if(p == null){
                PageReference pageRef = new PageReference('/apex/demo2');
                return pageRef;
            }
            else{
                return null;
            }
    }
    
  • You can use cookies

    Set cookie

    Cookie elementMsg = new Cookie('msg','true','/apex/pageYouAreGoingToUse',10,false);

    Add to the current page

    ApexPages.currentPage().setCookies(new Cookie[]{elementMsg});

    Redirect to the page you want

    return new PageReference('/apex/CompetencyAssessmentOne?id=' + Assessment.id );

    Take the cookie from the page you are going to use the cookie

    Cookie elementMsg = ApexPages.currentPage().getCookies().get('msg');

    Use the cookie

            if(elementMsg != null){
    
            if(elementMsg.getValue().equals('true')){
                elementMsg = new Cookie('msg','true',null,0,false);
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Elements saved'));
            }
        }
    
  • I would recommend you to read through this doc to understand how pagereference works in apex:

    https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_system_pagereference.htm

    Coming to your question this should do what you want:

    public demoController(){
    String p = ApexPages.currentPage().getParameters().get('param');
    if(p == null){
    callpageredirect();
    }
    }
    public pagereference callpageredirect(){
    PageReference demoPage = new pagereferenct('/apex/demo2');
        demoPage.setRedirect(true);
        return demoPage;
    }
    

    It's not working. I already tried it. The function returns the PageReference to the constructor, and that's it. Page doesn't get redirected.

License under CC-BY-SA with attribution


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