How to get the current sandbox-name programmatically (dynamically) via APEX?

Now after all mere subscribers has per default a lot of sandboxes available, I need a way to programmatically (dynamically) get the sandbox-name of the sandbox org where the actual code is executed.

Just for clarification: I’m not looking for the name of the org, but the name of the sandbox, which are two different things.

One example purpose for this requirement is to tag notification emails, so that it’s clear which sandbox-org has created it. For sure I don’t want to hardcode it. Also I don’t want to use a custom setting.

If found a few unclean approaches like

  • UserInfo.getUserName().substringAfterLast('.'); ==> this is not reliable, username might have been changed or a system-user might act. But this comes closest to what I need.

  • use of Organization.IsSandbox ==> not good enough, does not tell me which of the 25+ possible sandboxes it is. Only that’s not production. I need more

  • use of Organization.Name ==> all the same for all sandboxes

  • use of Organization.InstanceName ==> provides the server name like CS83, very nice, but not good enough

I think there is no officially supported way to get it… but I’m not 100% sure…

Is there any approach to “hack” that sandbox name out of the guts of the platform? I need no sample code, just an idea or a concept is good enough for me.

Answer

After Spring’16 release there is an ability to specify an Apex class which executes every time the sandbox is copied. See SandboxPostCopy Interface. You can get the sandbox name from SandboxContext and store it in a custom setting. Notice the example indicates this method signature exists: SandboxContext.sandboxName().

global class HelloWorld implements SandboxPostCopy {
    global void runApexClass(SandboxContext context) {
        System.debug('Hello Tester Pester ' + context.organizationId() + ' 
                  ' + context.sandboxId() + context.sandboxName());
    }
}

Attribution
Source : Link , Question Author : Uwe Heim , Answer Author : Adrian Larson

Leave a Comment