+ Start a Discussion
Nik'sNik's 

How can i Convert Lead Programmatically ?

I am wrting the test method for trigger OnLeadConvert . How can i convert "Lead" in Test Method ?

Best Answer chosen by Admin (Salesforce Developers) 
Darshan ShahDarshan Shah

Lead objLead = new Lead();
objLead.Company = 'Test1';
objLead.Status = 'Open';
objLead.LastName = 'TestLastName';
insert objLead;

 

Database.Leadconvert lc = new Database.Leadconvert();
lc.setLeadId(objLead.id);
LeadStatus convertStatus = [select id,MasterLabel from LeadStatus where isConverted=true limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);

 

System.debug('LeadConvertResult AccountId : '+ lcr.getAccountId());
System.debug('ContactId : '+ lcr.getContactId());
System.debug('LeadId : '+ lcr.getLeadId());
System.debug('OpportunityId : '+ lcr.getOpportunityId());

All Answers

Darshan ShahDarshan Shah

Lead objLead = new Lead();
objLead.Company = 'Test1';
objLead.Status = 'Open';
objLead.LastName = 'TestLastName';
insert objLead;

 

Database.Leadconvert lc = new Database.Leadconvert();
lc.setLeadId(objLead.id);
LeadStatus convertStatus = [select id,MasterLabel from LeadStatus where isConverted=true limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);

 

System.debug('LeadConvertResult AccountId : '+ lcr.getAccountId());
System.debug('ContactId : '+ lcr.getContactId());
System.debug('LeadId : '+ lcr.getLeadId());
System.debug('OpportunityId : '+ lcr.getOpportunityId());

This was selected as the best answer
Nik'sNik's

Thank you darshan .. it Works fine..

 

 

 Cheers..

 Thank's.

Colin KenworthyColin Kenworthy
Starting API v36.0 you should no longer use MasterLabel, your code could fail - use ApiName instead:
LeadStatus convertStatus = [select id,ApiName from LeadStatus where isConverted=true limit 1];
lc.setConvertedStatus(convertStatus.ApiName);