Two Ways To Determine A Salesforce Org Type
Have you ever created code or customisations that you only want to run within a sandbox or a production environment, and wanted an easy way to determine the org type?
Option 1- Apex
Create a utility class, as per the example below, then you can call this in your Apex class as per the following example. This utility class query for the current Salesforce Environment’s base URL, then using string methods determining if the URL contains CS.
public class Utility {
public static Boolean sandboxBool;
public static Boolean isSandbox()
{
if ( sandboxBool == null ) sandboxBool = URL.getSalesforceBaseUrl().getHost().left(2).equalsignorecase('cs');
return sandboxBool;
}
}
Example Controller/Trigger calling
system.debug(' o ' + Utility.isSandbox());
' If Statement Example
If(Utility.isSandbox())
{
' Run this code, as current environment is a sandbox
}
Option 2 — SOQL
Another way to determine if your in a sanbox or not is via querying the object. This is a good alternative to the pure Apex approach shown in Option 1, however this does consume a SOQL query — so you need to consider the context of when you need to use this.
SELECT Id, IsSandbox, Name FROM Organization LIMIT 1
Example of how you can use the query:
Organization currentOrg = [SELECT Id, IsSandbox, Name FROM Organization LIMIT 1];
If(currentOrg.IsSandbox == True)
{
System.Debug('Your in a sandbox!');
}