function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Determine SalesForce instance or URL in code

Hi everyone.  

   Is there a Apex class method to get current instance or URL at runtime?

I want to generate hyperlinks like{accountId} in code.  But I don't want to hard code 'na4'.

Every time I deploy the same code back to Sandbox, I must fix the instance manually.

Thanks in advance.

Curious... I have always used{accountId} and it seems to always auto-correct itself to the proper nsX.  Have you tried that?
That's interesting.  I thought the instance does not change at all.  I will try that out. 

I'm curious if 'na1' construct is a wild card to replace the instance in sandbox too (e.g. cs1 instance).

Is there a document about na1 construct?

To tell you the truth I just tried it with some expectation that it was going to break and some hope that thier system would just auto correct.

The short answer is that it works, and I hope it's a feature and not a bug that they will later fix.  LOL!


We have the same problem. Rt now we are checking for the org id and if it is production, we use na5, if not we use tapp0. But even this has a problem. Sandbox's instance may change after a refresh. This would be a problem in HTML email templates also.I hope there will be some function(s) to retrieve the current orgs's url. 


The folowing idea might work too. User's session id contains details of the instance. The letter after "00D" determines the instance. If it is "T" then the instance is tapp0.


T - tapp0

S - cs1

R - cs2

Q - cs3

P -  cs4 and so on

And it doesn't correct itself. If the instance changes, it asks you to login again and redirects according to your login name (sb1, sb2, etc)

Where are you putting the url?


In visualforce, if you use an apex:outputlink you can set the value = "/{!ID}" or "/apex/..." and the output control takes care of it for you.  Works on Page Redirects in APEX too. 


Frick'n Emoticons! LOL! Always gets me.


should be like <apex: outputlink> 


hope that worked. 



	public String getInstanceName()
		return (Userinfo.getOrganizationId() == '00AA0000000DclC') ? 'Production' : 'Sandbox';

Here is the unit test



	static testMethod void testGetInstanceName()
		String expected;
		expected = 'Production';
		expected = 'Sandbox';


You could use the above to return NA4 / CS2 as necessary.



This works!!




We're using URL.getSalesforceBaseURL().toExternalForm(), but it's returning since the code is being called from a Sites page.  =[