How to open a new Tab using PageReference in apex class?

We can use apex:commandLink to redirect a visualforce page in a new Tab URL using PageReference in apex class.

Sample Code:

VF Page:

<apex:page controller="SampleleRedirect">
	<apex:form >
		<apex:pageblock >
			<apex:commandlink action="{!redirect}" target="_blank">
				<apex:commandButton value="Open in New Tab"/>
			</apex:commandLink>
		</apex:pageblock>
	</apex:form>
</apex:page> 

Apex Controller:

public class SampleleRedirect {   

	public SampleleRedirect() {
	
	}

	public pageReference redirect() {
		PageReference pageRef = new PageReference('http://www.biswajeetsamal.com');
		pageRef.setRedirect(true);
		return pageRef;
	}            
}

  • Siddhartha Charles Xaviers Gho

    Hi Biswajit,

    how to open a visualforce page from an apex method withoud any button click .
    FOr example, I click on a button on a standard account detail page and the button calls an apex method..now the apex method inserts some contacts ..and after inserting it opens up a visualforce page

    Please let me know if this is possible..

    Regards,
    SIddhartha

    • As i understood from your requirement, you have one custom button and you are calling an apex method to do some functionality after complete that you want to redirect to a VF page.

      You can return success or failed from your apex method and in the custom button javascript, check the return message, if it is success then redirect to a vf page using javascript.

      • Siddhartha Charles Xaviers Gho

        Hi Biswajeet Da,

        I have a account standard detail page button(on click Java Script)……on clicking the button, the button sends account id and account external id to a Apex method……work of the button is completed

        then that function calls another function

        now in that function…..

        if (response.getBody() == ‘{}’)
        {
        /////// I need to call the vf page which just shows an alert
        }

        or can we call a pop-up from the class itself so the vf isn’t required….or maybe some kind of apex message or anything….
        I am quite stuck in this

        Regards,
        SIddhartha

      • Siddhartha Charles Xaviers Gho

        I tried something like this

        if (response.getBody() == ‘{}’)
        {
        System.Debug(‘I need to call the vf page which just shows an alert’);
        classname.opennewvf();
        }

        public static PageReference opennewvf()
        {
        System.Debug(‘External Id unavailable’);
        PageReference vfPage1 = new PageReference(‘apex/MyVf’);
        vfPage1.setRedirect(true);
        return vfPage1;
        }

        The System.Debug(‘External Id unavailable’) is working in the method
        the page reference is having the values but the VISUALFORCE page is not opening on the account detail page…..

        • Don’t redirect to VF page from apex class, redirect from javascript button