Thursday 10 December 2015

How to get sandbox name in apex?

As we all know sandbox username looks like "behera@mycompany.com.dev "

dev- is the sandbox name, How can we get it this dynamically ?

Use below code :-

if(UserInfo.getUserName().substringAfterLast('.com')!= null)
                    contact.Email = contactInfo.Email+'.'+UserInfo.getUserName().substringAfterLast('.');
                else
                    contact.Email = contactInfo.Email;
}

UserInfo.getUserName().substringAfterLast('.') - will give you sandbox name.

UserInfo.getUserName().substringAfterLast('.com') will tell you whether anything is there after " .com ". if not there that means we are in production otherwise in sandbox. 
We can also used same method to identify type of org like prod or non prod. There is another approach for this. 

Organization org = [select id,IsSandbox from Organization];
org.IsSandbox = true if it a sandbox. It willwork classs of higher version.

Feel free to suggest more.

4 comments:

Anonymous said...

Many thanks for this!!

-- David B

Anonymous said...

Many thanks for this!

-- David.

Test said...

Thank you for this

Unknown said...

From Spring' 22 release

System.Domain d = System.DomainParser.parse(URL.getOrgDomainUrl());
System.debug(d.getSandboxName());

ref: https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_domain_classes.htm&type=5&release=236