0

I have the following Visualforce page that overrides the "View" action of a standard object:

<apex:page standardController="Opportunity" extensions="OpportunityDispatcherCx" action="{!redirect}"/>

This is my controller:

public class OpportunityDispatcherCx {
    // Opportunity Variable
    Opportunity oOpportunity {get;set;} 

    public OpportunityDispatcherCx(ApexPages.standardController stdController) {
        oOpportunity = [Select Id, Amount
                        From Opportunity
                        Where Id = :stdController.getId()];
    }

    public PageReference redirect() {
        // Construct a redirection url
        String redirectUrl = '';

        // Make your checks
        if(oOpportunity.Amount < 100) {
            redirectUrl = '/apex/errorPage?id=' + oOpportunity.Id;
        }else {
            redirectUrl = '/' + oOpportunity.Id;
        }

        // Set a pageReference for redirection
        PageReference pageRef = new PageReference(redirectUrl);

        // Return it for the redirection
        return pageRef;
    }
}

However, when an Opportunity amount is over 100, the code will be called again and again for every successful redirection, leading to infinite recursion. What is the solution?

1

You need to handle this in your code, to make sure it doesn't redirect second time.

    //Just check if your page contains extra parameter retur null
    if(Apexpages.currentpage().getparameters().containsKey('noredirect'))
         return null;
    // Construct a redirection url
    String redirectUrl = '';

    // Make your checks
    if(oOpportunity.Amount < 100) {
        redirectUrl = '/apex/errorPage?id=' + oOpportunity.Id;
    }else {
        redirectUrl = '/' + oOpportunity.Id+'?noredirect=true';
    }
    //this code will only work first time.
    // Set a pageReference for redirection
    PageReference pageRef = new PageReference(redirectUrl);
    // Return it for the redirection
    return pageRef;

or better as you are already on detail page so instead of redirecting, Just return null.

    // Make your checks
    if(oOpportunity.Amount < 100) {
        redirectUrl = '/apex/errorPage?id=' + oOpportunity.Id;
    }else {
        return null; //just return from here
    }

    // Set a pageReference for redirection
    PageReference pageRef = new PageReference(redirectUrl);

    // Return it for the redirection
    return pageRef;

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.