[SalesForce] URL Encoding in Apex – PageReference to Merge Accounts

Following to my previous question – Merge Accounts based on Account Number.

I have written a Visualforce page with a selectable table list of Accounts.
When selecting the accounts and pressing the action Button I've added – it's calling a PageReference Method that direct the user to the standard Merge Account Page link and will transfer the Id's of the selected accounts as parameters.

This is nice since I extended the standard Merge page Criterias with my Queries..and I don't need to find duplicates based only on the Account Name.

So Basically I want to populate the following link with selected account Id's.

 /merge/accmergewizard.jsp?goNext=+Next+&cid={!selectedAccount1.Id}&cid={!selectedAccount2.Id}

Problem is that when I'm building the URL String and hit the button – the URL get messed up.

For Example :

public PageReference mergeAccounts ()     {

    String mergeURL = '/merge/accmergewizard.jsp?';
    String pageURL ='goNext=+Next+';
    String accIdvar = '&' + cid + '=';
    String URLAccount1 = accIdvar + selectedAccounts[0].Id;
    String URLAccount2 = accIdvar + selectedAccounts[1].Id;

    String URL = mergeURL + pageURL + URLAccount1 + URLAccount2;

    PageReference pageRef = new PageReference(URL.escapeHtml4());
    pageRef.setRedirect(true);
    return pageRef;

    }

The result URL when using this method is :

/merge/accmergewizard.jsp?amp%3Bcid=00124000007eGoVAAU&goNext=+Next+

So I need to encode it somehow and escape the '&' and the '=' – those Special chars thats seems to be the ones that creates the problem – the link is backward and has been cut off.

Suggestions anyone? escape the '&' without messing up the URL?

Best Answer

Don't escape the URL that you pass into the PageReference constructor. This will result in Bad Things happening. Also, you shouldn't use escapeHtml* methods, because that's for a different purpose (encoding HTML so it doesn't render as HTML when viewed as HTML). Instead, you would use EncodingUtil.urlEncode if you needed to escape parameters, which you don't, because you're using normal ID values.

However, all of the information I've just provided is useless in this case, because PageReference is going to mangle your URL anyways-- you can't have duplicate parameters in a PageReference query string. You'll need to invent a different way of redirecting the user without using a PageReference, such as by depositing the URL into a plain string that's later injected into a script that performs the redirect:

<script>
    window.top.location.href = '{!newLocation}';
</script>