Skip to Content

TheBlogReaders.com

Salesforce.com, PHP, MySQL, Javascript, Ajax, Htacces

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

Be First!
by September 25, 2015 APEX, SALESFORCE, Trigger

Automatically convert Lead to Contact using Apex Trigger

Salesforce-DeveloperRequirement:
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.setLeadId(lead.Id);
//lc.setAccountId(AccountId); // you can set the AccountId instead of create a new account and contact is created the mention account
lc.setSendNotificationEmail(false);
lc.setOpportunityName(opportunityName);
//lc.setDoNotCreateOpportunity(true); // Optional to create a Opportunity
lc.setConvertedStatus(convertStatus.MasterLabel);
leadConverts.add(lc);
}
}
if (!leadConverts.isEmpty()) {
List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
}
}

Test Class:

@isTest
private class TestLeadTrigger {
static testMethod void TestLeadTrigger() {
Test.startTest();
Lead l = new Lead(FirstName = 'FName', LastName = 'LName', Company = 'Test Account', Status = 'Open', Email='info@theblogreaders.com');
insert l;
system.assertEquals(l.FirstName, 'FName');
test.stopTest();

}
}

Source:
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‘,

(933)

Previous
Next

Leave a Reply