Follow up to Spring ’16 Feature – Run Script for Sandbox

A follow-up post to and the Spring ’16 release feature Run Script after Sandbox Create or Refresh.

This was the original use case I wanted to cover (pending a support case and bug issues), functionality to auto refresh a custom setting with environment information.

In a production environment I have a custom setting (hierarchy type) that contains the environment Id, Name, Type, and URL.


…and it has the following data:


When a sandbox is created or refreshed from the production environment it pulls the custom setting data with it, but in this use case, it no longer relevant for the environment. I’m coming from the production environment, but I now want the relevant Sandbox environment information.  Now with an apex class that implements SandboxPostCopy interface, I can have this data auto populated when the sandbox is created or refreshed.  Here’s what the apex class looks like:

global class sandboxCreateRefreshScript implements SandboxPostCopy

global void runApexClass(SandboxContext context)

Environment_Settings__c es = Environment_Settings__c.getorgdefaults();

es.Environment_Type__c = 'Sandbox';
es.Environment_URL__c = URL.getSalesforceBaseUrl().toexternalform();
es.Environment_Id__c = String.valueof(context.sandboxId());
es.Environment_Name__c = context.sandboxName();
update es;


and test class…..

private class sandboxCreateRefreshScriptTest
@testSetup static void testData()
Environment_Settings__c es = new Environment_Settings__c();
es.Name = 'test';
insert es;
@isTest static void testSandboxPostCopyScript()

sandboxCreateRefreshScript sandboxScriptclass = new sandboxCreateRefreshScript();
Test.testSandboxPostCopyScript(sandboxScriptclass, UserInfo.getOrganizationId(), UserInfo.getOrganizationId(), 'sandboxName');

Environment_Settings__c es2 = Environment_Settings__c.getorgdefaults();
system.assertNotEquals(null, es2.Environment_Id__c);

On the sandbox wizard you’ll see we have the option of specifying the apex class to run that has the SandboxPostCopy interface.  Simply input the class name and submit.



After the sandbox refreshes, we now have our data auto populated:

Screen Shot 2016-04-25 at 12.05.34 PM