SFDX Developer Guide
SFDX Developer Guide
SFDX - Salesforce Developer ExperienceThis doc explains the SFDX concepts in detail and it's solely based on my analysis and understanding. - Rajesh Babu Yanamala
How to install SFDX on my machine?
For Mac OS - https://sfdc.co/sfdx_cli_osxFor Windows 32-bit - https://sfdc.co/sfdx_cli_win
For Windows 64-bit - https://sfdc.co/sfdx_cli_win64
- Select the defaults, then install it in your machine.
- Once it's installed in our machine, then we need to verify whether it has been installed correctly.
- For that, we need to open the Command Prompt from our machine and type the command “sfdx”
- In order to check the version of the CLI, you can use the following command,
- -To see the installed plugins for SFDX CLI, then type this command,
- To know the Salesforce version that's used in our CLI which you have installed, type this,
==> If you are not sure about the commands in SFDX, you can see them at any time by typing,
sfdx force:doc:commands:list
or else you can type this “sfdx force --help”
sfdx help
- Then you can use the following command for example,
- For example, you would like to create an apex. For that, I need to see which command is available,
- If you would like to know about the VF page creation, then type
--> How to create an SFDX org or How can I use this SFDX CLI in my org?
We can have the functionality to spin a new SFDX org (DevHub org) with our normal production orgs.But still, you can have the option to sign up for a new trial org by just visiting this URL.
==> Please go to this URL, https://developer.salesforce.com/promotions/orgs/dx-signup and sign up for an Org.
(If you sign up for a trial org like this, we can be able to access the org for only 30 days, after that, either we need to renew the org by purchasing a license or else the org can be disposed after 60 days.)
- You can turn your Production org into a new Dev Hub Org. (Production org means any DE, EE, UE orgs).
- Login to your Production org and go to Setup and then search for “Dev Hub”.
- You can see the option to enable the DevHub, then please select theoption. That's it, your org can behave now as a Dev Hub org.
- Then you can see some new tabs got created for you namely, Scratch Org Infos and Active Scratch orgs.
- You can check and Manage the complete scratch org information with the help these two tabs.
Once after your DevHub org is ready, then you can authenticate the org via CLI and start creating new scratch orgs and play with them.
What is a Scratch Org ?
The scratch org is a source-driven and disposable deployment of Salesforce code and metadata. A scratch org is fully configurable, allowing developers to emulate different Salesforce editions with different features and preferences.- Scratch org is exactly similar to a typical Sandbox but it is a temporary sandbox, where it can be self disposed after its life span.
- The default life time for a scratch org was 7 Days. But we can have the ability to extend this life span till 30 days, but we need to specify this at the time of creation of scratch org.
- For a normal DE org, it can have the capability to hold 6 scratch orgs, where only 3 sctratch orgs could remain active and 3 could remain Inactive.
- For other Editions, certain limits would be there, but these could be modified by raising a case with our Salesforce. Depending upon the criteria, we can either modify or deny the request.
How to Link my DX Org to my SFDX CLI ?
Once you create a Trial edition org (DX org), then keep the username and password in handy.
Then open the command prompt, and remember the command which I told you earlier.
If you are not sure how to type any command, just use help command (mentioned as earlier) and then use the command for authentication.
We will pick the last command for now. We will discuss the remaining commands later.
Type the command as, sfdx force:auth:web:login -a tango@mango.com
(in the above command, tango@mango.com is my DevHub username. You can use yours),
then, it will automatically pop out a browser window and ask us for credentials for login.
For the first time, after entering the credentials, it will ask us to enable the access to use the SFDX CLI.
So the SFDX CLI works as an OAUTH connection.
You can verify this step by cross-checking the Login History of your org as,
If you check the Apps section also, you can find the OAUTH connection that created automatically after giving the access while logging in for the first time. Please find the screenshot as shown below,
==> Now check your DevHub org once,
( Disclaimer:- I already have created this org, so it is showing as 21 days remaining and I am also having the scratch orgs in my DevHub).
The answer is No. You cannot create any new scratch org from the UI.
==> We can create any scratch org from the command prompt (CLI tool) only.
Then we can go for Scratch org section.
Before going to scratch org, we can learn about the creation of Project in our repository.
In order to play with scratch orgs, we need to create a Project. A Salesforce DX project has a specific structure and a configuration file that identifies the directory as a Salesforce DX project.
You can learn more about the project using the link as shown below,
https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_create_new.htm
Now, we need to use the command to create a project,
sfdx force:project:create -n DemoSfdxProject
- sfdx-project.json
- config/project-scratch-def.json
- .forceignore
==> We need to be careful about these files. Because the file “config/project-scratch-def.json” is responsible for Scratch org creation and the file “sfdx-project.json” helps us in shaping our project.
== > For creating the Scratch org, we need to use the following command,
sfdx force:org:create -f config/project-scratch-def.json -a MyDemoOrg
Now we need to note down the username of the scratch org which we created and the Org ID.
We can cross check the org via UI also. I mean in DevHub org as well.
==> Why and How this happened?
Yes, because of the file “config/project-scratch-def.json”. It has the following code inside it,
{
"orgName": "Demo Company",
"edition": "Developer",
"orgPreferences" : {
"enabled": ["S1DesktopEnabled"]
}
}
So, this is the Org shape. We can modify it as per our convenience.
For suppose, I can change the org name and we can include some features. Please see the below code,
{ "orgName": "Acme", "country": "US", "edition": "Enterprise", "description": "Work Item #12345: add picklist to widget", "hasSampleData": "true", "features": ["MultiCurrency", "AuthorApex"], "orgPreferences": { "enabled": ["S1DesktopEnabled", "ChatterEnabled"], "disabled": ["IsNameSuffixEnabled"] } }
We can find more about the configuration values under this link,
https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_scratch_orgs_def_file_config_values.htm
==> Now we have created the scratch org for our DevHub, How can I open this Scratch org?
- Via UI or command prompt?
- I did not have a password with me, it just showed,
- How can I open this org without any password?
sfdx force:org:open -u test-pheyglxh4iv8@example.com
It uses cookies to open the scratch, so no need to provide the password now, we are already providing a unique username.
==> How can I generate the password for the scratch org?
sfdx force:user:password:generate --targetusername test-pheyglxh4iv8@example.com
sfdx force:user:display --targetusername test-pheyglxh4iv8@example.com
- For example, I have changed my password via UI, but the command prompt still showing my old password only. It cannot display my latest password.
=> For that we need to manually set the default devhub username. So that it will point to that username only and we need to set the corresponding scratch org for that DevHub environment as well.
sfdx force:config:set defaultdevhubusername=tango@mango.com
sfdx force:config:set defaultusername=test-pheyglxh4iv8@example.com
Use the command as, sfdx force:org:list
==> Aliasing :-
- Here in SFDX, we can play everything with Alias names.
- For example, we can set an alias name to our DevHub org as dOrg1 and Scratch org as sOrg1.
sfdx force:alias:set dOrg1=tango@mango.com
- This command will set the alias name as dOrg1 for the DevHub org having the username of tango@mango.com.
- We can set multiple alias names in a single command by separating the alias names with spaces,
sfdx force:alias:set dOrg1=tango@mango.com sOrg1=test-pheyglxh4iv8@example.com
sfdx force:org:list
- The org names of DevHub and Scratch orgs changed to their Alias names.
- Aliasing is just like a shortcut.
- Suppose If I have a scenario where I need to execute 20 commands repeatedly for a presentation or any demo with our client or our customer. What we do is, we need to type each and every command manually. This would cause a huge delay in terms of execution and it's a time-consuming process.
- If we set alias name for those commands, then it would be easy for us to execute those commands in a fraction of seconds and it would create an impression to others that we are experts while executing these commands.
Authorization of DevHub and Scratch orgs
Why do we need to authorize again? Already, we have authorized our dev org and scratch org right...The answer is, we can authorize our org in 3 different ways.
- using Web-based flow
- using JWT flow (with the help of OAUTH)
Authorizing an Org using Username and Password :-
Yes, we already know how to login to our DevHub and scratch org and login via web.
Authorizing an Org using Web Based Flow :-
-- First step is to make sure no orgs should be active in our CLI command prompt. (Please logout of all the Orgs that were connected to the CLI)
-- Need to find the correct port which is free from any connections.
-- Set the correct port number in "sfdx-project.json" file, For Example,
-- Then create a new Connected App configuration in the DevHub org.
Please follow this article for creating the app,
https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth_connected_app.htm
-- Then please note down the consumer key and consumer secret from the connected app, later we can use the same for Login.
-- Then please try to modify the login commands as shown below,
sfdx force:auth:web:login --clientid <my org consumer key> --setdefaultdevhubusername --setalias <give an alias name for your org>
- Then it will ask you "OAuth client secret of personal connected app?:" like this. Then you need to enter the client secret.
-- That's it, it will take you to login page, after entering your credentials, it will allow us for login.
-- Then you can start creating a new scratch org for this org. I hope this would create a new scratch org with our disturbing the existing OAUTH configuration.
-- By this way, you could at least try to create a new scratch org using new oauth configuration.
This is the easiest way to authorize the DevHub using the web-based flow.
If we want to login to our scratch org using the web based flow, then we need to explicitly add the instance URL as
sfdx force:auth:web:login --setalias my-hub-org --instanceurl https://test.salesforce.com
Then it will allow us to login to the scratch org.
Authorizing an Org using JWT Flow (with the help of OAUTH):-
Prerequisite:- We need to install the OpenSSL in our machine to generate a digital certificate and private key.
Steps to install the OpenSSL in our machine and generate a digital certificate:-
Please catch up the doc on this URL:-
To Authorize our DevHub using JWT, Please follow the steps,
- We can just simply run the
sfdx force:auth:jwt:grant
command and pass required parameters to it. Then it will directly authenticate our defined connected app using the consumer key and the private key which we defined already. - Then the command looks like,
In the above command, we are saying that it needs to validate the clientId (consumer key), and we are passing the private key as the client secret. So it will validate our certificate and client ID and allow us to authenticate the DevHub org.
C:\Users\ryanamala\Videos\JWTDemo\Demo1>sfdx force:auth:jwt:grant --clientid 3MVG9pe2TCoA1Pf7pde1T9h.AGoVyCrSXBopYOsL1XYYcfVcnwH4Lb1HYIVm4kySyo9c1Z.R1NQ7HPySXmqrx --jwtkeyfile C:\Users\ryanamala\jdoe\JWT\server.key --username rajeshmailme@sfdx.com
Successfully authorized rajeshmailme@sfdx.com with org ID 00D0o000001BOdfEAG
For the same command, we can some extra parameters as well to make it very clear. Please note the below commands are optional.
--instanceurl
https://test.salesforce.com (if the org is a scratch org)--instanceurl
https://login.salesforce.com (no need to mention this for DevHub, by default it will use this URL https://login.salesforce.com)--setdefaultdevhubusername --setalias my-hub-org
So, if I frame the entire command at one place, then it will look like this,
C:\Users\ryanamala\Videos\JWTDemo\Demo1>sfdx force:auth:jwt:grant --clientid 3MVG9pe2TCoA1Pf7pde1T9h.AGoVyCrSXBopYOsL1XYYcfVcnwH4Lb1HYIVm4kySyo9c1Z.R1NQ7HPySXmqrx --jwtkeyfile C:\Users\ryanamala\jdoe\JWT\server.key --username rajeshmailme@sfdx.com --instanceurl https://login.salesforce.com --setdefaultdevhubusername —setalias my-hub-org
Successfully authorized rajeshmailme@sfdx.com with org ID 00D0o000001BOdfEAG
This way of authorization is very useful in CI / CD processes, because, no need to explicitly look for any org for authorization.
Then we can discuss about Scratch Org authorization using JWT flow.
So, if we want to authorize the scratch org, we need the instance url as https://test.salesforce.com and we can use the same consumer key and private key which we defined for the devHub.
So, after the creation of scratch org, please wait for approx. 5 minutes, then you will be able to see the scratch org configuration under the DevHub as,
Then, frame the command as shown below,
C:\Users\ryanamala\Videos\JWTDemo\Demo1>sfdx force:auth:jwt:grant --clientid 3MVG9pe2TCoA1Pf7pde1T9h.AGoVyCrSXBopYOsL1XYYcfVcnwH4Lb1HYIVm4kySyo9c1Z.R1NQ7HPySXmqrx --jwtkeyfile C:\Users\ryanamala\jdoe\JWT\server.key --username test-vsthx2qpt5ji@example.com --instanceurl https://test.salesforce.com
Successfully authorized test-vsthx2qpt5ji@example.com with org ID 00DN0000000RKEUMA4
We have used the same consumer key and private key and changed the instance URL.
By this way, we can be able to authorize the scratch org and DevHub using the JWT flow.
Scratch Orgs
==> So everything is at the place now. We can discuss what we can do with our Scratch org.==> In our scratch org, I am thinking to create an Apex Class and store the same in my local repository. How can I do that?
==> This is so simple. Open your scratch org and go to setup→ build → develop→ Apex classes. Create an Apex class.
==> Now we open the command prompt and ask the CLI, what changes were made recently to our scratch org.
sfdx force:source:status
--> We can check the recent changes that we performed by using this command.
==> Now we can store this class in our local repository by using the following command,
sfdx force:source:pull
- We can even check the same by going to the path,
==> Why can't we create an Apex Class via command prompt?
Yes, we can create the same via CLI as well.
sfdx force:apex:class:create -n DemoDxClass
sfdx force:source:status
==> Now we can upload the Apex class into our scratch org from our repository by using the following command,
sfdx force:source:push
==> We can verify the same in our UI as well,
Pull - Pulling the changes that we made in UI (scratch org) to our Local Repository (in our PC).
Well, I got a doubt here. I am able to write an Apex Class and synchronize my changes between my Scratch org and my Local Repository.
In a real-time scenario, if I write an Apex class, I will test that using the developer console or any other third party tool.
How can I do the same here? Will SFDX CLI allow me to test my Apex Classes?
==> YES, you can test the apex classes from the CLI itself, no need to depend upon the Developer Console or any other automated third-party tools. That's why this CLI tool is called ALL IN ONE.
==> Let us take this scenario little further.
Open your CLI and authenticate your scratch org. Try to write an apex class from UI or develop it from the CLI tool.
Here, I am developing the apex class and its corresponding test class from the CLI tool.
sfdx force:apex:test:run
This command will execute all the test classes present in our Org. It's just like Run All Tests option in UI.
sfdx force:apex:test:report --testrunid 707N000001o0t6J
For every test class ID which we give, this will give us a detailed report mentioning the status of test class execution as shown below,
-- You can just specify the synchronous parameter to the command along with the specific test class name. That's it !!
sfdx force:apex:test:run --synchronous --classnames TestMathCalculator
I can even run the test class and view the result of the test class in a different format. The possible values for viewing the result format would be human, tap, junit, json.
sfdx force:apex:test:run --classnames TestMathCalculator --resultformat tap --codecoverage --wait 10
Here, I just mentioned the test class and changing the result format to tap format to view the code coverage and we are imposing a waiting period of 10 seconds. Since its an asynchronous execution, we are explicitly specifying the waiting period.
sfdx force:apex:test:report -i 707N000001o0uUV --resultformat human
This command will give us the results in Human format and its the default format to view the results.
This command will give us the results in JSON format, i.e. Key-Value pair.
This command will give us the results in JUNIT format. This is very easy to understand.
I got a doubt. Suppose, if my apex class is having 10 methods inside it, can I run only 2 specific methods?
-- YES, we can !!
sfdx force:apex:test:run --tests TestClass.MethodA, TestClass.MethodB
Since I do not have any extra methods in my test class, I am unable to show it as an example here. But the syntax is the same as shown above.
Debug Logs
Can we enable Debug logs while performing any scenario like executing any apex class or any other operations?
The answer is YES, we can get the Debug logs in CLI directly.
Example:- I have an apex class and I am executing the test class. I can see the Debug logs in CLI tools.
sfdx force:apex:test:run
So in this scenario, I have already opened the Developer Console and executed the test run command.
By this way, I got the log file similar to the Developer Console.
We can just copy the Debug Log File ID and fetch the complete log using the command
sfdx force:apex:log:get --logid 07LN000000lj6FjMAI
Add Namespace to our DevHub:-
Generally, in our DE, we will directly define a namespace to our Org. This namespace is mainly used for packaging.But when it comes to DX, we cannot define any namespace to our DevHub org.
“But we can clone the namespace of an existing DE org to our DevHubOrg”.
How to link NameSpace to DevHub org:-Login to your DE org first and check whether you have any namespace defined there.
- Please refer this doc, for further reference to define a namespace to our organization, “https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/namespaces_creating.htm“
Please check your namespace as shown above and proceed to link the same to your DevHub org.
- (Make sure you are using any random namespace for your testing purpose, but please use your desired namespace for your development perspective)
-- There would not be any NameSpace registered to your org. Then click ”Go" button next to the “All NameSpace Registries” view.
=> Now, you will see a button “Link NameSpace”.
We need to login to our DE org from the popup window, so it will grab the namespace of our DE org.
It should look like this,
Please find the screenshot here,
--> You can link a number of NameSpace registries depend upon the requirement. There is no compulsion that we need to work only with one namespace.
Can I copy the settings and permission from one org to another?
Have you ever wondered that if we can clone a complete org into a new org irrespective of the org editions?Is it possible to copy the settings and permissions from one org to another org, without creating them manually after the org creation?
The ANSWER is YES. We have that functionality to create or clone an org which can copy or inherit the permissions from the parent org which we can specify.
Note:- This feature will just copy the permissions and settings and features only, but not the org's metadata or real time data.
And YES, it reduces our manual effort, to set and configure the permissions and settings in any new org.
Here is the link which can explain us about the concepts along with the complete parameters, https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_org.htm?search_text=password#cli_reference_shape_create
I am going to explain them briefly, so you can have a complete idea on the same.
Our Salesforce has released a feature called “Org Shape”, which is the most awaiting feature from our Partners and many other customers to copy and clone the contents from one org to another org.
Now, we can discuss about cloning an org.
org:shape:create
Packaging in SFDX
Package Types:-- First Generation Packages
- Unlocked Packages
- Second Generation Packages
==> My sincere advice, please complete these trailhead modules to know more about the Unlocked Packages.
https://trailhead.salesforce.com/en/projects/quick-start-unlocked-packages
https://trailhead.salesforce.com/trails/sfdx_get_started/modules/unlocked-packages-for-customers
>> The First and foremost point, “If we are creating a Managed Second generation package, then a Namespace is required for our DevHub. But if we want to create an Unlocked package, then namespace is optional”.
>> Another point to note. If we want to develop any unlocked package or second generation packages in our org, then we need to enable the permission “Enable Unlocked Packages and Second-Generation Managed Packages (Beta)”.
How to create an Unlocked Package:-
- Create a new Project or use the same old project path which you are using in your local machine. (for example purpose, I am creating a new project and demonstrate this scenario).
- Then try to add any components (like any apex classes, VF pages etc..) to your “force-app” folder. I am assuming that in my machine, I have added the components which I developed and what components which I desired to be there in my Package.
- Here, I have added 2 apex classes and making the package with those two components only.
- Be sure to run the package CLI commands from the directory that contains the
sfdx-project.json
file.
- As of now, my “
sfdx-project.json"
file looks like this,
- Use the command “sfdx force:package:create --name "MyUnlockedPkg" --path force-app --packagetype Unlocked”
--> Now, we can take a look at the “
sfdx-project.json"
file, it should get modified with the new package that we created just now.- We are not passing any namespace here to the sfdx-project.json file, so the package would be an unlocked package without a namespace.
==> Notice the placeholder values for versionName and versionNumber. You can update these values, or indicate base packages that this package depends on. You can specify the features and org preferences required for the metadata of your package in the project file, or you can opt to specify this information in an external
.json
file, such as the scratch org definition.- Now we can create a version to this package and see what happens,
for example, I have taken installation key as “rajesh20”, the command looks like,
sfdx force:package:version:create --package "MyUnlockedPkg" --installationkey rajesh20 --definitionfile config/project-scratch-def.json --wait 10
*** If we do not give the installation key, it will throw us the reasonable error saying that it requires the installation key.
.json
file on the command line or define it in the sfdx-project.json
. Wait a few minutes before you proceed to the next step.==> After creating this new version, the “
sfdx-project.json"
file looks like,- So far, we have created an unlocked package and added the components in it and created a new version for that package.
- Now, we need to install this package into our Scratch org.
- So, we need to use the command “sfdx force:package:install --package "MyUnlockedPkg" -u MyOrg12 --installationkey rajesh20 --wait 10 --publishwait 10”
** As you can see from the above “
sfdx-project.json"
file screenshot, the package got upgraded to newer version and the package Alias name also got changed to “MyUnlockedPkg@0.1.0-1”.So we need to give the latest version Alias name to the above command.
- Now the command will look like, “sfdx force:package:install --package "MyUnlockedPkg@0.1.0-1" -u MyOrg12 --installationkey rajesh20 --wait 10 --publishwait 10”
- Woohoo !! We have successfully installed this Unlocked package into our Scratch org.
==> Let's create an Unlocked package with a NameSpace in our org.
The steps are almost same, we need to add any component in our local repository and start packaging the added components.
- But we need to specify the “namespace” in our sfdx-project.json file as shown below,
- These would be our next steps to create an unlocked package with namespace.
- Now the version also created, so the sfdx-project.json file looks like this,
- So, from the above screenshot, we are good to install this namespaced unlocked manage in any Scratch org. But from now, we need to copy the package ID and use it where ever we need to install this package.
- I have created a new scratch org and my intention is to install this newly created package into newly created scratch org.
- Here --p parameter refers to the default path that we are specifying. So I am creating a new project in my same project path. This is optional.
- Then, we are good to install this package into the scratch org.
sfdx force:package:install --package 04t0o000000qu95AAA --targetusername test-x7ujm5rawojg@example.com --installationkey rajesh20
sfdx force:package:install:report -i 0HfN00000000Db5KAE -u test-x7ujm5rawojg@example.com
- We can check the same in UI as well, by opening the scratch org,
- By this way, we can cross check whether the package got installed correctly and the components does have the exact namespace as we specified or not.
## This is the best way to create a namespaced unlocked package in our org. Cheers !!
Really good, Thanks for sharing
ReplyDeleteSalesforce Online Training