Wednesday, December 14, 2011

Safe URLs for use with Salesforce Custom Buttons/Links and PageReferences

I encountered an issue today with an inherited Salesforce App and references to custom Visualforce pages. As they were, the references would work fine in the development sandbox or when deployed via an unmanaged package. However, when they were deployed via a managed package with the associated namespace the links from the custom buttons would break.

The custom button would have a link to the Visualforce page like:


The issue is the missing namespace prefix from the Visualforce page when used in a managed package.

To resolve this the Visualforce page reference should be done using URLFOR. Ideally with some form of explicit reference to the page like this:

{!URLFOR($Page.TheVisualforcePage,'',[param1 =])}

However, the $Page Global Variable isn't an available function and results in an error. To help resolve this please go to IdeaExchange: Custom Button: Expose $Page in the URL Content Type and promote the idea.

The same issue occurs within the Apex code with PageReference. There were a number of instances like:

Pagereference ref = new Pagereference('/apex/TheVisualforcePage?param1=' + opportunityId);

The preferred method was to use explicit references to the page.

PageReference p = Page.TheVisualforcePage;

See Also: