Sub topic 11
Automating Conversion and Assignment with Apex
This chapter assumes you know how assignment rules and lead conversion work in the UI. It also assumes you can read basic Apex and SOQL. Here you will run assignment rules from code, convert leads with Database.convertLead, and read the results.
Why Apex needs explicit options
Assignment rules run automatically when a lead is created through the UI or Web-to-Lead with the right settings. Apex does not work that way. A lead inserted from Apex keeps the owner you give it, or defaults to the running user, unless you ask for the rule to run.
You ask through Database.DMLOptions. Setting assignmentRuleHeader.useDefaultRule to true runs the active assignment rule. You can instead set assignmentRuleHeader.assignmentRuleId to run a specific rule.
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;The options must be attached to the record with setOptions before the DML statement. If you set an owner explicitly in the constructor and also enable the rule, the rule result wins when an entry matches. If no entry matches, the lead goes to the default lead owner defined on the rule.
Converting a lead with Database.convertLead
Conversion needs three things:
- The Id of an unconverted lead.
- A Lead Status value that is marked as converted.
- A
Database.LeadConvertobject that describes the outcome.
You query the converted status instead of hard-coding it, because admins can rename status values.
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());This creates a new account and a new contact and skips the opportunity. The lead's field mappings apply exactly as they do in the UI.
The diagram below shows the flow of the call.
Converting into existing records
To attach the lead to records that already exist, set their Ids on the LeadConvert object before converting.
setAccountIdconverts into an existing account.setContactIdmerges into an existing contact. The contact must belong to the chosen account.setOpportunityNamenames the new opportunity. LeavesetDoNotCreateOpportunityatfalseto create one.setOwnerIdsets the owner of the new records.
Unlike the UI, Database.convertLead does not search for duplicates for you. Your code must decide which account or contact to use, typically by querying on email or domain first.
Handling results and bulk calls
Database.convertLead has a list overload that accepts up to 100 LeadConvert objects per call. Pass a list when converting many leads, and check each result. A failed conversion returns a result with isSuccess() equal to false, and getErrors() explains why.
List<Database.LeadConvert> converts = new List<Database.LeadConvert>();
// ... add LeadConvert objects ...
List<Database.LeadConvertResult> results = Database.convertLead(converts, false);
for (Database.LeadConvertResult r : results) {
if (!r.isSuccess()) {
for (Database.Error e : r.getErrors()) {
System.debug(e.getStatusCode() + ': ' + e.getMessage());
}
}
}The second argument, false, allows partial success. With the default behavior, one failure rolls back the whole call.
Reading the results afterward
After conversion, the lead stays in the database with IsConverted = true. It points to the records that conversion created or updated.
SELECT Id, Name, ConvertedDate, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId
FROM Lead
WHERE IsConverted = true
ORDER BY ConvertedDate DESC
LIMIT 10Common errors
| Symptom | Likely cause |
|---|---|
| Lead owner is the running user after insert | `DMLOptions` not set, or not attached with `setOptions` |
| `INVALID_STATUS` on conversion | The status used is not marked as converted |
| Contact merge fails | The contact is not on the account you supplied |
| `ALREADY_CONVERTED` style failure | The lead was converted earlier. Filter on `IsConverted = false` |
Exercise
A trigger inserts leads from a partner feed, but every lead is owned by the integration user, even though an active assignment rule exists. What do you change?
Show answer
Create a Database.DMLOptions object, set assignmentRuleHeader.useDefaultRule to true, and attach it to each lead with setOptions before the insert. Apex DML does not run assignment rules unless you request them.