Sub topic 12
Database.DMLOptions for field truncation and other behaviors
This chapter assumes you can write try/catch blocks in Apex and that you know how Database.insert(records, false) returns one SaveResult per record. It also assumes you know DML runs inside a transaction with governor limits. Earlier chapters used the allOrNone Boolean to switch between all-or-nothing and partial success. This chapter covers Database.DMLOptions, an object that carries that setting plus several others.
What DMLOptions is
Database.DMLOptions is a class that bundles save-time settings. You create one, set properties on it, and pass it to a Database method. It replaces the plain Boolean allOrNone argument when you need more than one setting.
The properties you will meet most often:
| Property | What it controls |
|---|---|
| `allowFieldTruncation` | Cuts over-long string values to fit the field instead of failing the record |
| `optAllOrNone` | The same all-or-none switch as the Boolean argument |
| `assignmentRuleHeader` | Whether Case or Lead assignment rules run on save |
| `emailHeader` | Whether automatic notification emails are sent |
| `duplicateRuleHeader` | How duplicate rules behave, for example allowing a save despite a duplicate warning |
| `localeOptions` | The locale used for labels in results and messages |
Only Database.insert and Database.update accept a DMLOptions argument. Database.upsert and Database.delete do not. Use the Boolean allOrNone there.
The diagram below shows where the options enter the save path.
Field truncation
By default, saving a string longer than the field allows fails that record with the status code STRING_TOO_LONG. Setting allowFieldTruncation to true tells the platform to cut the value to the field's maximum length and save the record.
Database.DMLOptions opts = new Database.DMLOptions();
opts.allowFieldTruncation = true;
opts.optAllOrNone = false;
List<Account> accounts = new List<Account>{
new Account(Name = 'A'.repeat(300))
};
List<Database.SaveResult> results = Database.insert(accounts, opts);
System.debug(results[0].isSuccess());
Account saved = [SELECT Name FROM Account WHERE Id = :results[0].getId()];
System.debug(saved.Name.length());The Name field on Account holds 255 characters. The first debug line prints true, and the second prints 255. Without the option, the record would fail with STRING_TOO_LONG.
Truncation applies to string values written to text-type fields. It does not repair other failures. A required field left blank, a bad picklist value, or a validation rule failure still fails the record.
The optAllOrNone default
optAllOrNone has the same meaning as the Boolean argument: true means one failure rolls back every record, and false allows partial success. Its default is true.
This catches people who switch from Database.insert(records, false) to a DMLOptions object and forget to set the property:
Database.DMLOptions opts = new Database.DMLOptions();
opts.allowFieldTruncation = true;
// optAllOrNone not set, so it stays true
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account() // missing required Name
};
List<Database.SaveResult> results = Database.insert(accounts, opts);Because optAllOrNone is still true, the second record fails and the first is rolled back. The call does not throw, which surprises people. In the Database methods, record-level failures come back in the results, not as an exception. Check isSuccess() on every result, and set opts.optAllOrNone = false whenever you want partial success.
Assignment rules
Case and Lead records created through the UI run assignment rules by default. Records created in Apex do not, unless you ask. The assignmentRuleHeader property controls this.
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
Case c = new Case(Subject = 'Printer offline', Origin = 'Web');
Database.SaveResult sr = Database.insert(c, dmo);
System.debug(sr.isSuccess());Set useDefaultRule = true to run the active default rule. Alternatively, set assignmentRuleId to run a specific rule. Do not set both. If you do, the call fails.
Using options with DML statements
The insert and update statements have no argument slot for options. To use options with a statement, attach them to the record with setOptions:
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
Lead l = new Lead(LastName = 'Rivera', Company = 'Globex');
l.setOptions(dmo);
insert l;This is the usual pattern for assignment rules, because it keeps the statement syntax. The options travel with that record. If you save a list, set the options on each record that needs them.
Using setOptions does not change how failures are reported. The statement still throws DmlException on any failure. If you also want partial success, use Database.insert with optAllOrNone = false.
Emails and duplicate rules
Two more headers show up in real code.
emailHeader controls notification emails that a save can trigger:
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.emailHeader.triggerUserEmail = true; // emails to users, such as new owner notices
dmo.emailHeader.triggerOtherEmail = false; // emails to contacts and other recipients
dmo.emailHeader.triggerAutoResponseEmail = false;duplicateRuleHeader decides what happens when a duplicate rule is set to alert instead of block:
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.duplicateRuleHeader.allowSave = true;
dmo.duplicateRuleHeader.runAsCurrentUser = true;
Contact c = new Contact(LastName = 'Smith', Email = '[email protected]');
Database.SaveResult sr = Database.insert(c, dmo);With allowSave = true, the record saves even when the rule finds a duplicate. Rules configured to block still block. Without the option, an alert-type rule makes the save fail with a DUPLICATES_DETECTED error. That error appears in getErrors() as a Database.DuplicateError, which is a subclass of Database.Error.
Reusing one options object
A single DMLOptions instance can be passed to several calls. Build it once at the top of a method. Do not rebuild it inside a loop. Creating the object does not count against DML limits, but each Database.insert or Database.update call still counts as one DML statement. Keep calls outside loops and pass whole lists, as in the bulkification chapter.
Database.DMLOptions opts = new Database.DMLOptions();
opts.allowFieldTruncation = true;
opts.optAllOrNone = false;
Database.SaveResult[] inserted = Database.insert(newRecords, opts);
Database.SaveResult[] updated = Database.update(existingRecords, opts);Common errors
- Expecting partial success from the defaults.
optAllOrNonedefaults totrue. Set it tofalseexplicitly. - Treating truncation as a safety net. It hides bad data. If a value should never exceed the limit, let it fail and fix the source.
- Passing options to upsert or delete. There is no overload. The compiler rejects it.
- Skipping the result check. A
Databasecall with options does not throw for record errors. Loop over the results and callisSuccess(). - Setting both
useDefaultRuleandassignmentRuleId. Choose one.
Choosing options or the Boolean
Use the Boolean allOrNone when partial success is the only thing you need, because it works on every Database method and reads clearly. Switch to DMLOptions when you also need truncation, assignment rules, email control, or duplicate handling. For assignment rules on a single record where you want exception behavior, setOptions with a DML statement is the shortest route.
Exercise
A developer writes Database.DMLOptions opts = new Database.DMLOptions(); opts.allowFieldTruncation = true; and calls Database.insert(records, opts) with 200 records. One record has a blank required field. What happens to the other 199 records, and why?
Show answer
None of them are saved. optAllOrNone defaults to true, so the single failure rolls back the whole call. The call does not throw. It returns 200 results, and the 199 valid records carry an error indicating they were rolled back because of the other failure. Setting opts.optAllOrNone = false would save the 199 valid records.
Exercise
You need new Case records created in Apex to run the default assignment rule, and you want a failed save to throw DmlException. Which approach fits, and which Database method overload could you not use for this?
Show answer
Create a Database.DMLOptions with assignmentRuleHeader.useDefaultRule = true, call setOptions on each Case, then use the insert statement, which throws DmlException on failure. You could not pass options to Database.upsert or Database.delete, because only Database.insert and Database.update accept a DMLOptions argument.