[SalesForce] Getting Communities Url from PageReference

I have a VisualForce page that I would like to open in a new tab via Javascript.

javascript (in VF page, called onClick)

function myFunction(){
   OpenInNewTab("{!url}");
}

Apex controller

public String getUrl(){
    return Page.MyPage.getUrl();
}

The URL that gets generated is the standard SF url /apex/mypage, but for the communities user it needs to be myCommunity/mypage.

Is there anyway to get the correct Url WITHOUT hardcoding the communities prefix in my code?

Best Answer

I stumbled across the same issue a couple of days ago. This is how I resolved it...

In my case it was a button (could be a link as well), I've added onclick javascript event to call a javascript function:

<input type="button" value="Proceed" onclick="redirectToMyPageJS();" />

Then I wrote my JS function which gets the community name from the URL:

<script>
    function redirectToMyPageJS()
    {
        // It's always the 3rd element in the list which is the community name when accessed from the communities site
        redirectToMyPage(window.location.href.split('/')[3]);
    }
</script>

and calls my action function passing the community name as a parameter:

<apex:actionFunction action="{!redirectToMyPage}" name="redirectToMyPage" >
    <apex:param value="" name="portalName" />
</apex:actionFunction>

Then finally in my APEX method I have:

public pageReference redirectToMyPage()
{
    return new PageReference('/' + Apexpages.currentPage().getParameters().get('portalName') + '/MyOtherPage');
}
Related Topic