Home SALESFORCEAPEX Automatically convert Lead to Account, Contact and Opportunity using Apex Trigger

Automatically convert Lead to Contact using Apex Trigger

Automatically convert Lead to Account, Contact and Opportunity using Apex Trigger if the Lead Status = Open

For Example:
Here we declare our trigger in Lead Obejct and name it as LeadAutoConverter and it will fire only after an insert the lead record.
trigger LeadAutoContactConverter on Lead (after insert) {

LeadStatus convertStatus = [Select MasterLabel from LeadStatus where IsConverted = true limit 1];

List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
for (Lead lead: Trigger.new) {
if (!lead.isConverted && lead.Status == ‘Open’ ) {
Database.LeadConvert lc = new Database.LeadConvert();
String opportunityName = lead.Name;

//lc.setAccountId(AccountId); // you can set the AccountId instead of create a new account and contact is created the mention account
//lc.setDoNotCreateOpportunity(true); // Optional to create a Opportunity
if (!leadConverts.isEmpty()) {
List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);

Test Class:

private class TestLeadTrigger {
static testMethod void TestLeadTrigger() {
Lead l = new Lead(FirstName = ‘FName’, LastName = ‘LName’, Company = ‘Test Account’, Status = ‘Open’, Email=’[email protected]’);
insert l;
system.assertEquals(l.FirstName, ‘FName’);


LeadConvert Class

Lead Validation Rule not working when converting Leads.
Resolution To enable the “Require validation for Converted Leads”
Go to your Name | Set-up | Customize | Leads | Settings
Enable “Require validation for Converted Leads”
Click on Save.

For information on Enabling ‘Use Apex Lead Convert‘,

You may also like

Leave a Comment