Sub topic 9
Deploying and Retrieving Source
This chapter covers moving source between your local DX project and your org. It assumes you have completed the earlier chapters: VS Code, the Salesforce CLI, a Java JDK, and the Extension Pack are installed, the project exists, and an org is authorized and set as the default. You should also be comfortable with the GreetingService class from the project.
The working model
A Salesforce DX project is a source of truth that lives on your disk, usually under version control. The org is a deployment target. Two operations connect them:
- Deploy sends local source files to the org. The org compiles Apex and validates metadata, and either accepts the change or rejects it.
- Retrieve pulls metadata from the org into local files, in source format.
Everything in VS Code's deploy and retrieve commands wraps the Salesforce CLI. The editor commands and the sf commands do the same work, so you can mix them.
Source tracking
Scratch orgs and some sandboxes support source tracking. The org records which components changed locally and remotely. With tracking, you can run "deploy" and "retrieve" without naming files, and the CLI sends or fetches only what changed. Production orgs and Developer Edition orgs do not support tracking. In those orgs you must name what to deploy or retrieve, by directory, file, or manifest.
If you are not sure which case you are in, use the explicit forms in this chapter. They work everywhere.
Deploying from the editor
The Apex extension adds commands to the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and to the Explorer context menu. The ones you will use most:
| Where | Command | What it does |
|---|---|---|
| Explorer, right-click a file or folder | SFDX: Deploy Source to Org | Deploys the selected file or folder |
| Editor, right-click inside a file | SFDX: Deploy This Source to Org | Deploys the open file |
| Explorer, right-click a file or folder | SFDX: Retrieve Source from Org | Retrieves the selected metadata from the org |
| Command Palette | SFDX: Deploy Source in Manifest to Org | Deploys everything listed in a `package.xml` |
| Command Palette | SFDX: Retrieve Source in Manifest from Org | Retrieves everything listed in a `package.xml` |
| Command Palette | SFDX: View Local Changes / View Remote Changes | Shows tracked changes (tracking orgs only) |
Command names change slightly between extension versions. If one is missing, type "SFDX: Deploy" in the Command Palette and read the list.
Try it
- Open
force-app/main/default/classes/GreetingService.cls. If you have not created it yet, create it with the content below, and keep theGreetingService.cls-meta.xmlfile next to it. - Right-click the file in the editor and choose SFDX: Deploy This Source to Org.
- Watch the Output panel, on the Salesforce CLI channel.
public with sharing class GreetingService {
public static String greet(String name) {
if (String.isBlank(name)) {
return 'Hello, world!';
}
return 'Hello, ' + name + '!';
}
}Every Apex class needs a metadata file with the same base name. VS Code creates it when you use SFDX: Create Apex Class. If you create the .cls file by hand, you must add the metadata file yourself:
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<status>Active</status>
</ApexClass>Without the -meta.xml file, the deploy fails with an error about missing metadata.
Deploying from the command line
The CLI equivalent deploys a whole directory:
sf project deploy start --source-dir force-appYou can narrow the scope. Each of these is a valid form:
# One file
sf project deploy start --source-dir force-app/main/default/classes/GreetingService.cls
# Several paths
sf project deploy start --source-dir force-app/main/default/classes force-app/main/default/triggers
# By metadata type and name
sf project deploy start --metadata ApexClass:GreetingService
# From a manifest
sf project deploy start --manifest manifest/package.xml
# Against a specific org instead of the default
sf project deploy start --source-dir force-app --target-org my-orgValidate before you deploy
A check-only deployment runs the same validation but saves nothing. It is useful before a production deployment.
sf project deploy validate --source-dir force-app --test-level RunLocalTestsThe deploy validate command requires a org that supports it, and production deployments of Apex normally require tests to run. Check your org's rules before relying on this.
Deploy results
A successful deploy prints a table of the components it changed, with a state of Created, Changed, or Unchanged. A failed deploy lists each problem with the file, line, and column. In VS Code, the Problems panel and the Output panel link the error to the location in the file.
A deployment is all or nothing for a given request by default. If one component fails, the whole request is rolled back.
Retrieving source
Retrieving is how you bring an org's configuration into the project. Common cases are a change made in Setup, a component built by someone else, or metadata you want to put under version control.
From the editor, right-click a file or folder and choose SFDX: Retrieve Source from Org. To retrieve something you do not have locally yet, use a manifest.
A manifest is an XML file, normally at manifest/package.xml, that lists metadata types and members:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>*</members>
<name>ApexClass</name>
</types>
<types>
<members>Account</members>
<name>CustomObject</name>
</types>
<version>62.0</version>
</Package>The * wildcard retrieves every component of that type. A few types, such as CustomObject for standard objects, need explicit names, so list those individually.
Retrieve with the CLI:
sf project retrieve start --manifest manifest/package.xml
sf project retrieve start --metadata ApexClass:GreetingService
sf project retrieve start --source-dir force-app/main/default/classesYou can also generate a manifest from your existing source:
sf project generate manifest --source-dir force-app --name packageRetrieve overwrites local files
A retrieve replaces the local copy of a component with the org's version. If you have unsaved or uncommitted local edits to that file, you lose them. Commit your work first. Without tracking, the CLI does not warn you about the difference.
With source tracking, a retrieve or deploy can stop on a conflict. That happens when both the local file and the org's copy changed since the last sync. The CLI then asks you to resolve it. You can override with --ignore-conflicts, but that discards one side, so use it deliberately.
Deploy on save
The extension can deploy a file every time you save it. Enable it in settings:
{
"salesforcedx-vscode-core.push-or-deploy-on-save.enabled": true
}This only suits an org where frequent deployment is safe, such as a scratch org or a personal sandbox. Do not enable it while the default org is production or a shared sandbox. Every save then changes a shared environment, and a half-finished edit that compiles will go live.
What a deploy does not do
- It does not delete. Removing a file locally does not remove the component from the org. Use
sf project delete sourcefor tracked deletions in supported orgs, or a destructive changes manifest. - It does not skip bad code. Apex that does not compile fails the whole request.
- It does not retrieve. After a deploy, local files stay as they were. Retrieve explicitly if the org changed the component, for example by adding fields.
- It does not run your tests unless the org requires it or you ask. Production deploys that include Apex run tests by default.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No default org found` or the status bar shows no org | No default org set for the project | Run `sf org login web --alias my-org --set-default`, or use **SFDX: Set a Default Org** |
| `Expired access/refresh token` | The org authorization lapsed | Authorize again with `sf org login web` |
| `Cannot find a metadata file` or missing meta error | `.cls` file without `-meta.xml` | Add the metadata file |
| `Variable does not exist` or `Invalid type` | The class depends on a component that is not in the org | Deploy the dependency first, or in the same request |
| Deploy reports `Unchanged` and you expected a change | You deployed the wrong path, or the file did not save | Save the file and check the path in the output |
| `API version` error | `sourceApiVersion` is higher than the org supports | Lower it in `sfdx-project.json` |
| Retrieve returns nothing for a type | The manifest lists the wrong type name or member | Check the exact API names |
To confirm which org a command used, read the first lines of the Output panel, or run:
sf config get target-org
sf org displayExercises
Exercise
You deleted OldHelper.cls from your project and ran a deploy of force-app. The class is still in the org. Why, and what can you do?
Show answer
A deploy only creates or updates components. It never deletes. Remove the component with sf project delete source (in an org that supports it), or deploy a destructive changes manifest, or delete it in Setup.
Exercise
A colleague changed GreetingService in your sandbox, and you have uncommitted local edits to the same file. You run sf project retrieve start --metadata ApexClass:GreetingService in a sandbox without source tracking. What happens to your edits, and how should you have prepared?
Show answer
The retrieved file replaces your local copy, and your edits are lost because there is no tracking to warn you. Commit or stash the changes first, then retrieve, then merge with Git.
Exercise
Write a command that deploys only the GreetingService class to an org with the alias my-org, without relying on the default org.
Show answer
sf project deploy start --metadata ApexClass:GreetingService --target-org my-org