Sub topic 12
Writing back to the external system
External objects are read-only by default. This chapter covers how to make them writable, how the Apex and UI write paths differ, and which failure modes to design for. It assumes you can create an external data source, run Validate and Sync, and write basic SOQL and Apex. It also assumes you have granted object permissions through permission sets, as in earlier chapters.
What "writable" means
Salesforce Connect does not store the data, so a write is a callout to the external system. The external system decides whether the write succeeds, and Salesforce records nothing about the row except a reference to it.
Three conditions must all hold for a write to work:
- The adapter supports writes. The OData 2.0, OData 4.0, and cross-org adapters do. A custom Apex adapter supports them only if you implement them.
- The external data source has Writable External Objects selected.
- The user has Create, Edit, or Delete permission on the external object, and the field is editable.
If the checkbox is cleared, DML on the object fails, even for an administrator.
Enabling writes
- In Setup, open External Data Sources and edit your data source.
- Select Writable External Objects.
- Save, then check that your named credential's identity is allowed to write in the external system.
The last step matters most. The checkbox only tells Salesforce to attempt the call. The external system still enforces its own authorization using the credential you configured. If it rejects the write, you get an error in the save result.
Then grant object permissions in a permission set. Read access does not imply write access, so select Create, Edit, and Delete only for the users who need them. Field permissions work the same way. A field the external system marks read-only stays read-only, whatever Salesforce permissions say.
Two write paths: immediate and asynchronous
Apex offers two ways to write to an external object. They differ in when the callout happens and how you learn the result.
| Method | When the callout runs | How you get the result |
|---|---|---|
| `Database.insertImmediate`, `updateImmediate`, `deleteImmediate` | During your code, synchronously | The returned `SaveResult` or `DeleteResult` is final |
| `Database.insertAsync`, `updateAsync`, `deleteAsync` | After your transaction finishes | The first result is pending. Use a callback or `Database.getAsyncSaveResult` |
| Standard DML such as `insert` | Asynchronously, like the `Async` methods | Not available to your code at save time |
The asynchronous path keeps your transaction from waiting on a slow system. It also means your code cannot assume the write succeeded when the call returns.
Immediate writes
An immediate write sends the change to the external system right away and returns the final outcome.
Product__x p = new Product__x(Name__c = 'Widget', Price__c = 25);
Database.SaveResult sr = Database.insertImmediate(p);
if (!sr.isSuccess()) {
System.debug(sr.getErrors()[0].getMessage());
}Check isSuccess() every time. A failed external write does not throw an exception when you use the Database methods, so ignoring the result hides the failure.
Updates and deletes need a record that already has a Salesforce Id. Query the record first, then change it:
Product__x p = [
SELECT Id, ExternalId, Price__c
FROM Product__x
WHERE Name__c = 'Widget'
LIMIT 1
];
p.Price__c = 30;
Database.SaveResult upd = Database.updateImmediate(p);
if (!upd.isSuccess()) {
System.debug('Update failed: ' + upd.getErrors()[0].getMessage());
}
Database.DeleteResult del = Database.deleteImmediate(p);
if (!del.isSuccess()) {
System.debug('Delete failed: ' + del.getErrors()[0].getMessage());
}The sample deletes the record right after updating it, only to show both calls. In real code, run each operation where you need it.
Asynchronous writes
With an asynchronous write, you receive the outcome later. You can poll for it, or you can give Salesforce a callback class to run when the external system responds.
public class ProductSaveCallback implements Database.AsyncSaveCallback {
public void processSaveResult(Database.SaveResult sr) {
if (sr.isSuccess()) {
System.debug('Created external record with Id ' + sr.getId());
} else {
System.debug('Create failed: ' + sr.getErrors()[0].getMessage());
}
}
}Product__x p = new Product__x(Name__c = 'Gadget', Price__c = 40);
Database.insertAsync(p, new ProductSaveCallback());If you do not need a callback, keep the returned SaveResult and pass it to Database.getAsyncSaveResult later to read the final state. Until the external system answers, the result reports no final success.
Choose a path by what the next step of your logic needs:
- Use an immediate write when later code depends on the new row. An example is creating a child record that points at it.
- Use an asynchronous write when the user should not wait on the external system and you can tolerate a delayed or failed outcome.
Writes through the UI
Users can create, edit, and delete external records from standard pages when they have the permissions and the data source is writable. These writes behave like standard DML, so they are asynchronous. A user may save a record and see it before the external system has confirmed the change. Later, a failure can leave the page showing a value that the external system rejected. Mention this in your design notes, because it is the most common surprise.
No transaction rollback
Writes to an external system fall outside the Salesforce database transaction. Two consequences follow:
- If an Apex transaction fails after an immediate write succeeded, Salesforce rolls back its own records, but the external row stays changed.
- A savepoint rollback does not undo an external write.
Retries create a related risk. If a callout times out, you cannot tell whether the external system applied the change. Retrying an insert might create a duplicate. Design the external API to be idempotent where you can, for example by sending a client-generated key the system uses to ignore repeats.
Identity of new records
For a created row, the external system usually assigns the key. Salesforce stores that key in the ExternalId field and creates its own Id for the reference. Do not choose or edit ExternalId yourself. Treat it as the external system's primary key, and read it back after a successful insert if you need it.
Limits and bulk behavior
Each write counts against callout limits, because it is an outbound call. Writing many rows can use up the per-transaction callout allowance, and a batch of external changes may also run into daily limits on Salesforce Connect usage. Check the current limits for your edition in the Salesforce documentation. A few habits help:
- Pass a list of records to one
Databasecall instead of looping over single records. - Do not write to external objects from a trigger that fires on frequent standard-object updates, since one bulk load can fan out into many callouts.
- Keep external writes out of tight loops, and move large jobs into Queueable or Batch Apex so that each execution gets its own limits.
Writes in a custom adapter
If you build an adapter with the Apex Connector Framework, writes are opt-in. Declare the capabilities in the provider, then implement the two methods on the connection.
override global List<DataSource.Capability> getCapabilities() {
return new List<DataSource.Capability>{
DataSource.Capability.ROW_QUERY,
DataSource.Capability.ROW_CREATE,
DataSource.Capability.ROW_UPDATE,
DataSource.Capability.ROW_DELETE
};
}override global List<DataSource.UpsertResult> upsertRows(DataSource.UpsertContext context) {
List<DataSource.UpsertResult> results = new List<DataSource.UpsertResult>();
for (Map<String, Object> row : context.rows) {
String externalId = (String) row.get('ExternalId');
try {
// Call the external API here. If externalId is null, create the row
// and use the key the API returns. Otherwise update the existing row.
if (externalId == null) {
externalId = 'new-' + String.valueOf(Crypto.getRandomInteger());
}
results.add(DataSource.UpsertResult.success(externalId));
} catch (Exception e) {
results.add(DataSource.UpsertResult.failure(externalId, e.getMessage()));
}
}
return results;
}
override global List<DataSource.DeleteResult> deleteRows(DataSource.DeleteContext context) {
List<DataSource.DeleteResult> results = new List<DataSource.DeleteResult>();
for (String externalId : context.externalIds) {
// Call the external API to remove the row.
results.add(DataSource.DeleteResult.success(externalId));
}
return results;
}Return one result per input row, in order, so Salesforce can match successes and failures to records. Use failure with a clear message so users and callers see why a write was rejected.
Troubleshooting
- "Writes are not enabled" or DML rejected: the data source does not have Writable External Objects selected, or the adapter does not support writes.
- Insufficient access: check the object and field permissions in the permission set, then check that the credential identity may write in the external system.
- Save works in the UI, but the value reverts: the asynchronous write failed after the page displayed it. Look at the callback result or the external system's logs.
- Duplicates after a timeout: the external system applied the first request, and your retry created another. Add an idempotency key.
- Read-only field: the external metadata marks the field as not editable, so the field is not updatable from Salesforce.
Exercise
A trigger on Opportunity must create a row in Product__x and then immediately create an Opportunity Line Item that depends on that row. The Opportunity is later rolled back because of a validation error. Which write method fits the dependency, and what happens to the external row?
Show answer
Use Database.insertImmediate, because the next step needs the final result of the external write. The Opportunity rollback does not undo the external row. It stays in the external system, so you need a compensating step (such as deleting it) or you should write it only after the Salesforce work is certain to succeed.
Exercise
A user saves an edit to an external record in the UI and sees the new value, but the external system later rejects it. Why does the page show the new value first, and where would you look for the failure?
Show answer
UI writes behave like standard DML, which is asynchronous, so the page shows the saved value before the external system answers. The failure appears in the final async save result, or in the external system's own logs.