I have a Visualforce page using a custom controller that is used to edit multiple records under an opportunity.
I'd like to create a custom button or link from Opportunities to this Visualforce page.
Currently the link looks like:
/apex/ExamplePage?oppId={!Opportunity.Id}
This works fine in the development sandbox, but when it is deployed as part of a managed package the link breaks as the page reference doesn't have the namespace prefix.
I found the post Managed Package Redirecting Problem on the Force.com Discussion Boards which implied it should be possible to use $Page to reference the Visualforce page in the URL. E.g.
{!URLFOR($Page.MyExamplePage,'',[objectId = campaign.id])}
But doing so only gives me the syntax error:
Error: Field $Page.MyExamplePage does not exist. Check spelling.
There is another part to the post that suggests using an Apex class and Execute Javascript to work around it. But it appears to me that this has just moved the namespace issue into the Javascript.
How can I safely reference the Visualforce page to work both inside and outside a managed package?
Best to do this from an Apex PageReference return value. Something like this will work:
Then call this from Visualforce:
The Apex Page call will handle the translation for you.
[EDIT]
Create a bare bones Visualforce page like this:
Add the above returnPage() method to a new TheController (or whatever) class. It doesn't even need a constructor. The class can look like this:
Then from the Opportunity settings page go to Buttons and Links and create a new custom Visualforce button selecting the new page you just created.
That should do it.
The post on the developer boards that you've linked to shows the following javascript being used for the button:
i.e. they're using javascript to call a webservice method in the class they've defined in order to get the page reference. Doing this would allow you to get the URL of the page in apex, where the managed package won't play an impacting part.
That said, the first parameter is the fully-qualified class name, so you could probably check the return value for an error (I don't know the error return value, so I'm assuming it's
null
here):Obviously you need to check what happens when
sforce.apex.execute()
fails, and you'll likely want some more error handling.It occurred to me that one less than ideal option would be to create two custom buttons in each case. One with the managed package namespace and one without.
When building the package the correct custom button could be selected.
One issue with this approach is the need to maintain two custom buttons.
It seems the answer is simply
/apex/package__Page
as provided here by @zachelrath. I can confirm this works in managed packages in production orgs as well as in development.