0
public class LeadConvert {
    public void convertToAccount(){
        account acc=new account();
        contact con=new contact();
        opportunity opp=new opportunity();
        list<contact>conlist=new list<contact>();
        list<opportunity>opplist=new list<opportunity>();
        list<account>acclist=new list<account>();
        list <Lead> ldList = [Select Name,Company,OwnerId,id From Lead];
        try{
            for(Lead ld : ldList){
                acc.name=ld.company;
                acc.Id=ld.Id;
                acc.OwnerId=ld.OwnerId;
                con.lastname=acc.name;    
                con.accountid=acc.id;
                opp.name=acc.name;
                opp.stagename='Prospecting';
                opp.closedate=system.today();
                opp.accountid=acc.id; 
            } 
            acclist.add(acc);
            conlist.add(con);
            opplist.add(opp);
            insert conlist;
            insert opplist;
            insert acclist;
        }  
        catch(Exception e)
        {
            system.debug(e);
        }
    }
}

2 Answers 2

1

Lead can converted using Database.LeadConvert. On conservion lead it will create the account, contact and opportunity(optional).

  public class LeadConvert {
  public void convertToAccount() {
    LeadStatus convertStatus = [select MasterLabel from LeadStatus where IsConverted = true limit 1];
    List <Database.LeadConvert> leadConverts = new List < Database.LeadConvert > ();

    for (Lead lead: [Select Name, Company, OwnerId, id From Lead]) {
      if (!lead.isConverted) {
        Database.LeadConvert lc = new Database.LeadConvert();
            
        lc.setLeadId(lead.Id);
        lc.setOpportunityName(lead.Name);
        lc.setConvertedStatus(convertStatus.MasterLabel);

        leadConverts.add(lc);
      }
    }

    if (!leadConverts.isEmpty()) {
      List < Database.LeadConvertResult > lcr = Database.convertLead(leadConverts);
    }
  }
}
2
  • Thank you @Amol. I saved this class in my org and run it using the Anonymous window..The result was null, nothing was converted. Can you tell me pls, what can I do to convert existing Leads into Account, Opportunities, and Contacts?
    – Aziz bek
    May 4, 2021 at 20:32
  • @Azizbek the same code is working. make sure you have valid record, and put debug log to check is record fetch by soql.
    – Amol
    May 5, 2021 at 11:25
0

You have to use LeadConvert Class, The convertLead Database method converts a lead into an account and contact or an account and person account, as well as (optionally) an opportunity.

Check out the link for help: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_dml_convertLead.htm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.