Sunday 29 June 2014

Lead Conversion in Apex

Here i am going to explain how to convert lead using apex code.
We have "ConvertLead()" method in apex to convert lead.To use this we just need to insert lead first after that we need to pass lead id into "setLeadId()" method as shown below.
Lead leadobj=new Lead();
leadobj.Company = 'AbC Company;
leadobj.LastName = 'Balaji';
insert leadobj;
//Passing lead id
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadobj.id);
//Getting converted status of lead from LeadStatus
//This is used to get Converted Status we set on lead with Lead Status field.
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
//setting convert status.
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr=Database.convertLead(lc);

After converting lead we can get ConvertedAccountId,ConvertedContactId,ConvertedOpportunityId.

Some times we don't want to create Account ,Contact from lead Conversion. Because those may be existing  with the same names. Then we can set existing AccountId, Contactid in lead conversion as shown in below.

Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadobj.id);  
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr=Database.convertLead(lc);
 lc.setLeadId(leadobj.id);
 lc.setAccountId(existingaccountId);  
 lc.setContactId(existingContactId);

If we do conversion with this method then we can have all the standard functionalities as in standard lead conversion.




1 comment:

  1. Where does this code live? is it in a trigger on Before/After update , or in a custom button? I'm really interested in this!! Thanks

    ReplyDelete

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...