Monday, March 9, 2020

Convert Lead using Apex in Salesforce

Sample Code
Lead objLead = new Lead();
objLead.LastName = 'Test Lead';
objLead.LeadSource = 'Website Lead';
objLead.Method_of_Contact__c = 'Phone';
objLead.Status = 'New Lead';
objLead.Phone = '1234567890';
insert objLead;

Database.LeadConvert leadCnvrt = new Database.LeadConvert();
leadCnvrt.setLeadId(objLead.id);

LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
leadCnvrt.setConvertedStatus(convertStatus.MasterLabel);

Database.LeadConvertResult leadCnvrtRes = Database.convertLead(leadCnvrt);
System.assert(leadCnvrtRes.isSuccess());

if(leadCnvrtRes.isSuccess()) {
 System.debug('Converted Opp Id ====> '+leadCnvrtRes.getOpportunityId();
 System.debug('Converted Acc Id ====> '+leadCnvrtRes.getAccountId();
}        

Resource
LeadConvertResult
LeadConvert Class

No comments:

Post a Comment