Press enter to see results or esc to cancel.

What are Scratch Orgs? How to work with them?

In the previous blog post we have seen how we can work with data using Salesforce cli. There is so much we can do with tree commands, I will cover them in another blog post. Now we will talk about what are scratch orgs and how to work with them and how they can be useful.
What are Scratch Orgs?
 
Scratch orgs are fully configurable, source driven and disposable Orgs. Phew.. That’s a Heavy statement.
Think of Scratch Orgs are like regular orgs only but you have the power in your hand to get the features what ever you want. Imagine if you need Person Accounts, Defer sharing recalculations … features you have to reach Salesforce and create a case with them to enable those options. With scratch orgs while creating them you can mention the features in the project-scratch-def.json file and it will take care of it.
Why do we need scratch orgs?
Well as per my understanding to proceed with modular ( Package Driven ) development you need Scratch Orgs.
In order to do some POC on features like Platform Encryption / Analytics.
If you need to recreate a problem that’s exist in one/two months old code base ( Leveraging SCM )
If you want a org like plain vanilla kind, you can leverage Scratch Orgs.
If you want to perform Automated Testing and delete the org.
Again these are some of the use cases I can think. There can be many use cases. Having said that as you work on these orgs you will learn more.
There are certain limitations on number of scratch orgs you can create based on the Org edition.
In order to create scratch orgs we need to enable the Dev Hub option in the Org. From Setup enter Dev Hub and enable the Dev Hub option.
Dev Hub
Optionally you can enable “Enable Unlocked Packages and Second-Generation Managed Packages”. We are not going to talk about it now.
Once you have enabled the Dev Hub now you can create scratch orgs. To create a scratch org you need a project-scratch-def.json file. which will have the options.
The above is the sample project-scratch-def.json I have created to create a scratch org. The features and settings values can be found here. You can configure the file as per your requirement.
Please visit the Metadata Coverage Report here on every metadata type you can see sample scratch definition.
Now that we have created project-scratch-def.json file with required features and settings. Now its time to create scratch orgs.
Create a standard project ( I am assuming you have already authenticated with devhub org )
Open Command Pallet by clicking Ctrl+Shift+P
Enter Scratch and select SFDX: Create a default Scratch Org..
Select the default project-scratch-def.json file.
Give your scratch org a alias name
Enter how many days you want the scratch org to live ( default is 7 days )
In the back-end Salesforce cli will run below command to create default scratch Org.
sfdx force:org:create -f configproject-scratch-def.json –setalias firstScratchOrg –durationdays 30 –setdefaultusername
But I ran into the issue like “The signup request failed because this organization has reached its active scratch org limit”
This means that I have consumed the maximum limit of scratch orgs i.e 3.

The signup request failed because this organization has reached its active scratch org limit

But how do you check. This can be checked two ways one is from UI and another is from using Salesforce CLI.
To know the limits in the org execute the command: sfdx force:limits:api:display and look for ActiveScratchOrgs. You can see there are no remaining left.

ActiveScratchOrgs

Now I have to delete some of these orgs. Question, How can I do that?
This also can be done on two ways either from UI / using Salesforce CLI. Execute the below command
sfdx force:org:delete -u me@my.org  replace the me@my.org with the username of the org you want to delete.
Lets create again the scratch org, This time it should work If everything is proper in project-scratch-def.json file and you have Active limit.
Execute the command: sfdx force:org:create -f configproject-scratch-def.json –setalias firstScratchOrg –durationdays 30 –setdefaultusername
If it is successful you will see something like this.
Successfully created scratch org: 00D9D0000000ag4UAA, username: dx9876@54321.com.
As we given this org as default username for this project. To open this org either you can click on the left corner button(left to the alias) VSCode or execute the command : sfdx force:org:open
You have successfully created the scratch org and opened it. Please check the settings/features yo have included in the  project-scratch-def.json enabled for your org or not.
In case if you need a preview org you need to include this setting “release”: “Preview” in your json file.
As we successfully created the scratch org, Its time to perform some metadata operations. As we are dealing with source format there is no space for mdapi in this use case.

Development & Deployment in Scratch Orgs

Create a sample Apex class:
 
  • Click Ctrl+Shift+P
  • Enter apex class select the command SFDX: Create Apex Class
  • Give it a name and your class is ready to use.
  • Create a system.debug statement inside constructor.
public with sharing class sampleClass {
    public sampleClass() {
            System.debug(‘Hello World!!!’);
    }
}

 

Now its time to deploy the changes to the scratch org.

sampleClass

  • Click Ctrl+Shift+P
  • Enter push select the command  SFDX: Push Source to Default Scratch Org
18:21:19.338 sfdx force:source:push –json –loglevel fatal
 ended with exit code 0

 

=== Pushed Source
STATE  FULL NAME    TYPE       PROJECT PATH                                           
─────  ───────────  ─────────  ───────────────────────────────────────────────────────
Add    sampleClass  ApexClass  force-appmaindefaultclassessampleClass.cls         
Add    sampleClass  ApexClass  force-appmaindefaultclassessampleClass.cls-meta.xml
Please check the output in the Output tab of terminal.
As we already opened the org lets go and create sample vf page and class. I have created testVfPage and sampleClassFromUi.
  • Click Ctrl+Shift+P
  • Enter pull select the command  SFDX: Pull Source from Default Scratch Org
Starting SFDX: Pull Source from Default Scratch Org

 

18:38:18.108 sfdx force:source:pull
=== Pulled Source
STATE  FULL NAME          TYPE       PROJECT PATH
─────  ─────────────────  ─────────  ─────────────────────────────────────────────────────────────
Add    testVfPage         ApexPage   force-appmaindefaultpagestestVfPage.page-meta.xml
Add    testVfPage         ApexPage   force-appmaindefaultpagestestVfPage.page
Add    sampleClassFromUi  ApexClass  force-appmaindefaultclassessampleClassFromUi.cls-meta.xml
Add    sampleClassFromUi  ApexClass  force-appmaindefaultclassessampleClassFromUi.cls
Add    Admin              Profile    force-appmaindefaultprofilesAdmin.profile-meta.xml
These are very basic metadata operations you can perform on scratch org. You can do whole bunch of things here, Most of the things you are doing in traditional way can be done using Salesforce CLI.
Ex:creating users, Assigning Permission sets etc..
NOTE: The commands we used in the above scenario only either push/pull the delta. That means only the changes that were present will be pulled/pushed. Underlying, Salesforce will be using source tracking feature to push/pull the delta. Only scratch orgs have this feature at the moment. Summer 20 Salesforce released this feature to sandboxes as beta.

Managing Scratch Orgs

Remember at the time of Scratch Org creation we have faced the issue. We have seen a way to overcome the issue using Salesforce CLI. There is even better option available i.e from UI.
  • Go to Salesforce Org (Dev Hub) then click on App Launcher
  • Type Scratch
  • open the Active Scratch Orgs and Scratch Org Infos in different tabs
  • From the Active Scratch Orgs tab select the All Active Scratch Org List View, Here you can find the all Active Scratch Orgs present.
  • Click on the drop down at the end of the record to perform operations like edit and delete.

All Active Scratch Org

Active Scratch Org
  • Go to Scratch Org Infos tab
  • Here you can find all the scratch Orgs list (deleted,active and error)
  • You can delete the records from here if you don’t want them. Keep in mind that deleting the Active record will also delete the scratch Org.
You can also use below query to find out the Scratch Org Infos:
SELECT AdminEmail,AuthCode,ConnectedAppCallbackUrl,ConnectedAppConsumerKey,Country,
CreatedById,CreatedDate,DeletedBy,DeletedDate,Description,DurationDays,Edition,ErrorCode,
ExpirationDate,Features,HasSampleData,Id,Instance,IsDeleted,Language,LastLoginDate,
LastModifiedById,LastModifiedDate,LastReferencedDate,LastViewedDate,LoginUrl,Name,
Namespace,OrgName,OwnerId,Package2AncestorIds,Release,ScratchOrg,SignupCountry,
SignupEmail,SignupInstance,SignupLanguage,SignupTrialDays,SignupUsername,Status,
SystemModstamp,Username FROM ScratchOrgInfo

Scratch Org Infos

As we go forward we will learn more about the Objects that were created when we enabled the Dev Hub option. How programmatically we can create scratch org using apex. Lets cover them in another blog post. I hope you enjoyed reading this blog post. Please let us know for any suggestions/queries in the comments section.