Sub topic 11
Automating conversion and assignment with Apex
This chapter covers two tasks you can do from code: running lead assignment rules when Apex saves a lead, and converting leads with Database.convertLead. It assumes you know how assignment rules and rule entries work, what happens during conversion, and how Lead Status marks a lead as converted. It also assumes you can read basic Apex and SOQL.
Why automate these steps
The UI runs assignment rules for you in some cases and offers a Convert button. Code gets neither by default. Typical reasons to write Apex for these steps:
- An integration or scheduled job creates leads, and they still need to reach the right owner or queue.
- A conversion needs logic the standard screen lacks, such as matching an existing contact by email and converting into it.
- Hundreds of leads qualify at once, for example after a campaign review, and nobody wants to convert them one at a time.
Running assignment rules from Apex
A lead inserted from Apex does not trigger assignment rules unless you ask for them. Without that request, the lead belongs to the running user, or to the default owner your code sets.
You request the rules through Database.DMLOptions:
Lead l = new Lead(
FirstName = 'Ada',
LastName = 'Lovelace',
Company = 'Analytical Engines Ltd',
Email = '[email protected]',
LeadSource = 'Web'
);
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
l.setOptions(dmo);
insert l;useDefaultRule = true runs the active lead assignment rule. Only one lead assignment rule can be active at a time. To run a specific rule instead, set assignmentRuleHeader.assignmentRuleId to that rule's ID. Set one of the two properties, not both.
You can also pass the options to the Database methods. This is useful for lists and for partial success:
List<Lead> leads = new List<Lead>{
new Lead(LastName = 'Hopper', Company = 'Compilers Inc', LeadSource = 'Web'),
new Lead(LastName = 'Turing', Company = 'Machines Ltd', LeadSource = 'Partner')
};
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
List<Database.SaveResult> results = Database.insert(leads, dmo);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
System.debug('Lead ' + i + ' failed: ' + results[i].getErrors()[0].getMessage());
}
}Options set with Database.insert(records, dmo) apply to every record in the call. Options set with setOptions apply to the one record.
Reassigning existing leads
Assignment rules also run on updates when you request them. To re-run the rules on leads that already exist, query them and update them with the options:
List<Lead> unowned = [
SELECT Id
FROM Lead
WHERE IsConverted = false AND LeadSource = 'Web'
LIMIT 200
];
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
Database.update(unowned, dmo);Running the rules on an update can change the owner of every lead in the list. Filter the list tightly, because existing owners get overwritten without warning.
Assignment inside triggers
Be careful when you want assignment from a Lead trigger. Changing a field in a before insert trigger does not by itself run the rules. A common pattern is to do the work after the save: an after insert handler (or a queued job) re-queries the new leads and updates them with the DML options. That second update fires your trigger again, so guard against recursion. A static Boolean flag in a handler class is the usual guard.
Converting leads with `Database.convertLead`
Conversion has its own API call. You do not set IsConverted = true on a lead yourself, because the platform rejects it. You build a Database.LeadConvert object for each lead and pass it to Database.convertLead.
The main LeadConvert methods:
| Method | Purpose |
|---|---|
| `setLeadId(Id)` | Required. The lead to convert. |
| `setConvertedStatus(String)` | Required. A Lead Status value marked as converted. |
| `setAccountId(Id)` | Convert into this existing account instead of creating one. |
| `setContactId(Id)` | Convert into this existing contact. Also set the account that owns it. |
| `setOpportunityId(Id)` | Attach to an existing opportunity. |
| `setDoNotCreateOpportunity(Boolean)` | Skip creating an opportunity. |
| `setOpportunityName(String)` | Name for the new opportunity. |
| `setOwnerId(Id)` | Owner of the new records. |
| `setOverwriteLeadSource(Boolean)` | Overwrite the contact's lead source with the lead's. |
| `setSendNotificationEmail(Boolean)` | Email the new owner. |
The simplest conversion creates a new account and contact:
LeadStatus convertStatus = [
SELECT MasterLabel
FROM LeadStatus
WHERE IsConverted = true
LIMIT 1
];
Lead l = [
SELECT Id
FROM Lead
WHERE IsConverted = false AND Email = '[email protected]'
LIMIT 1
];
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(l.Id);
lc.setConvertedStatus(convertStatus.MasterLabel);
lc.setDoNotCreateOpportunity(true);
Database.LeadConvertResult result = Database.convertLead(lc);
System.debug('Success: ' + result.isSuccess());
System.debug('Account: ' + result.getAccountId());
System.debug('Contact: ' + result.getContactId());The converted status must exist, or the call fails. Your org may have several converted statuses, and LIMIT 1 takes an arbitrary one. In production code, filter on a status you name, such as AND MasterLabel = 'Qualified', or read it from custom metadata.
Reading the results
LeadConvertResult exposes isSuccess(), getErrors(), getLeadId(), getAccountId(), getContactId(), and getOpportunityId(). The opportunity ID is null when you skipped opportunity creation.
The records created are also recorded on the lead. This query reads them back:
SELECT Id, Name, ConvertedDate, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId
FROM Lead
WHERE IsConverted = true
ORDER BY ConvertedDate DESC
LIMIT 10All-or-none behavior
Database.convertLead(lc) throws a DmlException if the conversion fails. Passing a second argument changes that:
Database.LeadConvertResult r = Database.convertLead(lc, false);With allOrNone = false, a failure comes back as an unsuccessful result, and you read r.getErrors(). The same applies to the list overload, where one bad lead does not stop the rest. For batch work, always use the list form with false, and handle failures from the results.
A bulk-safe service: convert into existing contacts
The standard Convert screen lets a user pick an existing account or contact. Code has to do the matching itself. This service matches each lead to a contact by email and converts into that contact's account. Leads with no match get a new account and contact.
public with sharing class LeadConversionService {
public static List<Database.LeadConvertResult> convertByEmail(List<Id> leadIds) {
LeadStatus convertStatus = [
SELECT MasterLabel
FROM LeadStatus
WHERE IsConverted = true
LIMIT 1
];
List<Lead> leads = [
SELECT Id, Email
FROM Lead
WHERE Id IN :leadIds AND IsConverted = false
];
Set<String> emails = new Set<String>();
for (Lead l : leads) {
if (l.Email != null) {
emails.add(l.Email.toLowerCase());
}
}
Map<String, Contact> contactsByEmail = new Map<String, Contact>();
for (Contact c : [
SELECT Id, AccountId, Email
FROM Contact
WHERE Email IN :emails AND AccountId != null
]) {
String key = c.Email.toLowerCase();
if (!contactsByEmail.containsKey(key)) {
contactsByEmail.put(key, c);
}
}
List<Database.LeadConvert> converts = new List<Database.LeadConvert>();
for (Lead l : leads) {
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(l.Id);
lc.setConvertedStatus(convertStatus.MasterLabel);
lc.setDoNotCreateOpportunity(true);
Contact match = l.Email == null ? null : contactsByEmail.get(l.Email.toLowerCase());
if (match != null) {
lc.setAccountId(match.AccountId);
lc.setContactId(match.Id);
}
converts.add(lc);
}
List<Database.LeadConvertResult> allResults = new List<Database.LeadConvertResult>();
Integer batchSize = 100;
for (Integer start = 0; start < converts.size(); start += batchSize) {
Integer finish = Math.min(start + batchSize, converts.size());
List<Database.LeadConvert> chunk = new List<Database.LeadConvert>();
for (Integer i = start; i < finish; i++) {
chunk.add(converts[i]);
}
allResults.addAll(Database.convertLead(chunk, false));
}
for (Database.LeadConvertResult r : allResults) {
if (!r.isSuccess()) {
System.debug(LoggingLevel.ERROR,
'Lead ' + r.getLeadId() + ' not converted: ' + r.getErrors()[0].getMessage());
}
}
return allResults;
}
}Points worth noting in this design:
- It runs one SOQL query for contacts, not one per lead.
- It builds the email set from lowercase values, and the map uses lowercase keys so matching stays consistent. Salesforce string comparison in SOQL is case-insensitive, but Apex map keys are case-sensitive.
- It sets the contact and its account together. Specifying a contact without its account is an error.
- It splits the work into groups of 100, because one
convertLeadcall accepts at most 100LeadConvertobjects. - It reports failures through the results rather than exceptions.
Flow of an automated conversion
Limits and side effects
- DML limits. Each
convertLeadcall counts as one DML statement against the 150-per-transaction limit. The rows it creates or updates count toward the 10,000 DML row limit. A batch of 100 leads can touch several hundred records, so run large jobs in Batch Apex with small scopes. - Triggers fire. Conversion updates the lead and inserts or updates accounts, contacts, and opportunities. Triggers, flows, and validation rules on all four objects run. A validation rule that requires a field the lead does not map can make conversion fail with a message you did not write.
- Field mapping applies. The lead field mapping you set up in Setup is used by the API too. Apex cannot override the mapping per call.
- Permissions. The running user needs the Convert Leads permission and Create access on the objects involved. With
with sharing, record access also applies to the matched contacts. - Duplicates. Active duplicate rules can block records created during conversion. The failure appears in
getErrors().
Common errors
| Symptom | Likely cause |
|---|---|
| Lead inserted from Apex has the wrong owner | `DMLOptions` not set, so no assignment rule ran |
| `INVALID_STATUS` or a similar status error | The converted status passed is not a converted Lead Status value |
| Error about the contact and account | Contact ID set without a matching account ID |
| Error that the list is too large | More than 100 `LeadConvert` objects in a single call |
| Conversion fails only for some leads | A validation rule, duplicate rule, or trigger on the new records rejected them |
Exercise
A scheduled job inserts 300 leads with insert leads; and the owners are not set by your active assignment rule. What two changes make the rule run, and how should you convert those leads afterward if the org processes them 300 at a time?
Show answer
First, create a Database.DMLOptions, set assignmentRuleHeader.useDefaultRule = true, and pass it with Database.insert(leads, dmo) (or call setOptions on each lead before a plain insert). Second, because inserts from Apex ignore assignment rules by default, this option is the only way the rule runs. For conversion, build one Database.LeadConvert per lead with the lead ID and a converted status. Call Database.convertLead in groups of at most 100, with allOrNone set to false. Then inspect each LeadConvertResult for errors, which means three calls for 300 leads.