+ Start a Discussion
canonwcanonw 

Determine SalesForce instance or URL in code

Hi everyone.  

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

I want to generate hyperlinks like https://na4.salesforce.com/{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.


SiriusBlackOpSiriusBlackOp
Curious... I have always used https://na1.salesforce.com/{accountId} and it seems to always auto-correct itself to the proper nsX.  Have you tried that?
canonwcanonw
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?
SiriusBlackOpSiriusBlackOp

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!

cogcog

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

cogcog
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)
SiriusBlackOpSiriusBlackOp

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. 

SiriusBlackOpSiriusBlackOp

Frick'n Emoticons! LOL! Always gets me.

 

should be like <apex: outputlink> 

 

hope that worked. 

bryan.gilbertbryan.gilbert

 

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

Here is the unit test

 

 

	static testMethod void testGetInstanceName()
	{
		String expected;
		expected = 'Production';
		expected = 'Sandbox';
		System.assertEquals(expected,getInstanceName());
	}

 

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

 

MohandaasMohandaas

This works!!

 

URL.getSalesforceBaseUrl().toExternalForm();



fgwarbfgwarb

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