Site icon WedgeCommerce

Convert Leads from APEX

In Salesforce, Lead is a very important record. We create leads for the sole purpose of keeping a track of people who are interested in our products. And why not these people are our potential customers. These leads are converted to account and contacts with the click of a button. However many think if we can do it with APEX code? Yes, we can with only a simple function. This is what I’ll explain, how to convert leads from APEX.

APEX code

For the purpose of this code, we will use the Database class. Create a new class in your developer console with this name ‘leadcon’, and paste the following code into it.

public class leadcon {
    
    public static void convert(string compName){
        list leads = [select id from lead where Company = :compName];
        list leadsToConvert = new list();
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        for(lead l: leads){
            Database.LeadConvert tempLC = new Database.LeadConvert();
            tempLC.setLeadId(l.id);
            tempLC.setConvertedStatus(convertStatus.MasterLabel);
            leadsToConvert.add(tempLC);
        }
        list lc = Database.convertLead(leadsToConvert);
        for(Database.LeadConvertResult lctemp: lc){
            system.debug(lctemp.getAccountId());
            system.debug(lctemp.getContactId());
        }
    }
}

Here we are putting each lead id in an individual leadconvert object and then passing the list of those ids to the convertlead method of the database class. Once this is done open the anonymous window and write the following line in it.

leadcon.convert('webkul');

For the purpose of this test I am using Webkul as the company name whose leads will be converted. You may use any name you may like from your Org.

Output

In order to test the output of my code, I have created a lead with the company name Webkul, as shown in the screenshot below.

Now I’ll run the code and check the log.

In the end, I’ll simply refresh the lead details page and see what we get.

Support

That’s all about how to convert leads from APEX, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views about this blog in the comments section below.

Exit mobile version