Avoiding Hard Coded URLs

Hopefully you know that hard coding links in Salesforce is a no-no. You might one day be migrated from one instance to another (NA1 to NA9999, or whatever they are up to these days). You also want to make sure that your links work in all your sandboxes. There is nothing worse than clicking on a link in a sandbox and all of a sudden you are in production!

First of all, I recommend that you implement My Domain. This means that you won’t have to worry about moving from one instance to another. Plus you need it on to use Lightning Components. You want those, right?

For the most part within Salesforce, you can just avoid the beginning part of the URL and use relative URLs. So, a URL button that takes you to a Visualforce page can just have ‘/apex/MyPage’.

The first “gotcha” is with managed packages. If you want to link to pages in a managed package, then you can still use a relative URL. Just use the format of ‘/apex/NAMESPACE__ManagedPage’.

Another good trick is to use the URLFOR function within Visualforce. This future proofs your pages so that if Salesforce ever changes the URL scheme (hello, Lightning), everything will still work. For example, to get the link to edit an account, I can use the following syntax.

{!URLFOR($Action.Account.Edit, account.id)}

Email templates are another tricky part of links. Since the email is being sent out, you can’t use relative URLs. You need to link into your instance. For the object that is triggering the email, you can use the merge field called Detail Link. This looks like {!Opportunity.Link}.

But what if you want to provide a link in your email to a related record? For example, an email gets sent from an opportunity, but you want a link to the account? First, let’s create a formula field on the object that will trigger the email and call it Base URL and make it a text formula field with the following formula:

LEFT($Api.Partner_Server_URL_360, FIND( '/services', $Api.Partner_Server_URL_360))

You can now use this formula field in your email templates to link to other records or Visualforce pages. So, from an opportunity email, the merge field would be: {!Opportunity.Base_URL__c}{!Opportunity.AccountId}.

By implementing these changes, you can be assured your links will always go to the correct instance.

One thought on “Avoiding Hard Coded URLs”

Leave a Reply