function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
NURHANIS BINTI MOHD ZARONINURHANIS BINTI MOHD ZARONI 

How to Convert a Lead to Opportunity & Contact based on existing account name using Apex

Dear all,
May i know if I can convert lead to only an existing account. the conversion will read based on company name in lead module. the apex now will create all new account, opportunty and contact ;

what i have done is creating a process builder that will run this apex when a lead becomes hot.



Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
               // Leadconvert.setDoNotCreateOpportunity(TRUE); Remove this line if you want to create an opportunity from Lead Conversion 
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}
Jay Wang 2Jay Wang 2
Hi,

If you want to convert the lead to an existing account you will need the account Id and then you just need to set it in the for loop.
LeadConvert.setAccountId('Insert Account Id here')
Although you'll need to query the Account or pass it in to the method.

Best of Luck,

Jay
 
NURHANIS BINTI MOHD ZARONINURHANIS BINTI MOHD ZARONI
Hi Jay,
i think your code above is just for set the lead coversion to only 1 account id right?

My concern is to bulkify my code so that it allow for 1 account to have multiple opportunties and contact tagged to it..
 
Jay Wang 2Jay Wang 2

Hi,

It can be bulkified, if you are matching the lead to the account by company name I would create a map with the company name as the key and the Account Id as the value. Will the company name from lead be the same as the account name? But something like the below example, can customise to your needs although I'm not sure if it is the best way to do it.

The method below assumes Account name is equal to Lead company.

List<Lead> leadList = [SELECT Company FROM Lead WHERE Id IN: LeadIds];
Set<String> companyList = new Set<String>();

for (Lead l : leadList) {
    companyList.add(l.Company);
}
List<Account> accList = [SELECT Name FROM Account WHERE Name IN: companyList];
Map<String, Id> mapOfAccName = new Map<String,Id>();

for (Account acc : accList) {
    mapOfAccName.put(acc.Name, acc.Id);
}
And then I would switch to looping through the list of leads rather than the Ids:
 
for (Lead l : leadList) {
    Database.LeadConvert Leadconvert = new Database.LeadConvert();
    Leadconvert.setLeadId(l.Id);                
    Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
    Leadconvert.setAccountId(mapOfAccName.get(l.Company));
    // Leadconvert.setDoNotCreateOpportunity(TRUE); Remove this line if you want to 
    create an opportunity from Lead Conversion 
    MassLeadconvert.add(Leadconvert);
}

Hope this helps, let me know if there's anything wrong or if you have anymore questions.

Best of luck,

Jay


 
NURHANIS BINTI MOHD ZARONINURHANIS BINTI MOHD ZARONI
dear jay,
i have implement your code above, but still getting error when i auto-convert the second lead :(

got the error 
Error element myRule_1_A1 (FlowActionCall).
An Apex error occurred: System.DmlException: ConvertLead failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: []

on the apex : 
Public class AutoConvertLeads4
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
       // List<Account>  paccountemail = new List<Account>();//adding this #1
                List<Lead> leadList = [SELECT Company FROM Lead WHERE Id IN: LeadIds];
                Set<String> companyList = new Set<String>();
                
                for (Lead l : leadList) {
                    companyList.add(l.Company);
                }
        
                List<Account> accList = [SELECT Name FROM Account WHERE Name IN: companyList];
                Map<String, Id> mapOfAccName = new Map<String,Id>();
                
                for (Account acc : accList) {
                    mapOfAccName.put(acc.Name, acc.Id);
                }
         
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for (Lead l : leadList) {
                            Database.LeadConvert Leadconvert = new Database.LeadConvert();
                            Leadconvert.setLeadId(l.Id);                
                            Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                            Leadconvert.setAccountId(mapOfAccName.get(l.Company));
                            // Leadconvert.setDoNotCreateOpportunity(TRUE); Remove this line if you want to 
                           // create an opportunity from Lead Conversion 
                            MassLeadconvert.add(Leadconvert);
                        }
        
   //     if (!MassLeadconvert.isEmpty()) {
     //       List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
      //  }
    }
}

on the process builder : 

User-added image

sorry im beginner in apex code..
 
Jay Wang 2Jay Wang 2

Hey,

Glad to see we're getting closer, I had a quick look up of the error and it seems the error could be 1 of 2 things. The first is that there are duplicate leads being fed in which you can solve by using Set<Id> leadList instead of List<Id> leadList. Try that one out first.

The more difficult but possible case is that you might not be able to convert multiple leads to the same account at the same time. If the first part does not work then let me know and I will have a look into it.

Kind Regards,

Jay

NURHANIS BINTI MOHD ZARONINURHANIS BINTI MOHD ZARONI
Hi Jay,  i have tried #1 option but it still worked like that.. urm

seems like it doesnt allow to convert multiple leads to the same account.. but the bisnes rule is 1 account may have multiple leads converted to opportunities and tagged to the same (existing) account.

How do I do this to eliminate the error..
Jay Wang 2Jay Wang 2
Hi,

Actually it seems that there could be an issue with the field mapping in the conversion. Try out this link https://help.salesforce.com/articleView?id=duplicate-value-found-On-Lead-Conversion&language=en_US&type=1.

To check the field mappings go to Object Manager->Lead->FIelds->Map Lead FIelds and double check the fields that are getting mapped and check to see if there are any fields that have the must be unique checkbox filled. That could be the issue.

Best of luck, 

Jay
NURHANIS BINTI MOHD ZARONINURHANIS BINTI MOHD ZARONI
hi jay, 
ive checked the map lead field, and seems only 2 field mapped to .
1. lead id (at opportunity tab)
2. Lead conversion - i have removed this and its field(is a unique checkbox)

continue to test the scenario and got this error ;

Error element myRule_1_A1 (FlowActionCall).
An Apex error occurred: System.DmlException: ConvertLead failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: []

Flow Details
Flow Name: Auto_Convert_Leads
Type: Record Change Process
Version: 5
Status: Active

Flow Interview Details
Interview Label: Auto_Convert_Leads-5_InterviewLabel
Current User: NURHANIS 
Start time: 05/09/2018 09:22
Duration: 0 seconds
How the Interview Started
NURHANIS  started the flow interview.
Some of this flow's variables were set when the interview started.
myVariable_old = null
myVariable_current = 00QO0000008NrpGMAS
ASSIGNMENT: myVariable_waitStartTimeAssignment
{!myVariable_waitStartTimeVariable} Equals {!$Flow.CurrentDateTime}
Result
{!myVariable_waitStartTimeVariable} = "05/09/2018 09:22"
DECISION: myDecision
Executed this outcome: myRule_1
Outcome conditions: and
1. {!myVariable_current.pi__campaign__c} (test) Is null false
Logic: All conditions must be true (AND)
AUTOCONVERTLEADS4 (APEX): myRule_1_A1
Inputs:
LeadList = {!myVariable_current} (00QO0000008NrpGMAS)



:((