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
James Roberts 32James Roberts 32 

Amend convert Lead apex to assign to existing account

I have a process set up on my website through a 3rd party tool whereby if someone downloads an asset, they complete a form and then are automatically loaded into Salesforce as a new Lead. I want to be able to automatically convert any new Leads that are created for Accounts that are already marked with type = Customer in Salesforce. 
 
I have created a Flow that is comparing the Company Name on a Lead to my Account Names with Type = Customer and if true, then calling the Apex class to convert the Lead. However, I would like to amend the Apex Class so that it does not create a new Account, but uses the existing account in the system. So in other words, create a contact only - no account, no opportunity. 

I think I need to use SetAccountId somewhere in the class, but I am not sure where or how to set the Account correctly - can anyone help?

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
            Leadconvert.setLeadId(LeadIds[0]);
            LeadStatus Leads= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            Leadconvert.setConvertedStatus(Leads.MasterLabel);
            Leadconvert.setDoNotCreateOpportunity(TRUE);
            Database.LeadConvertResult Leadconverts = Database.convertLead(Leadconvert);
            System.assert(Leadconverts.isSuccess());
   }
}
Khan AnasKhan Anas (Salesforce Developers) 
Hi James,

Greetings to you!

There is no way you can stop Account creation on Lead Conversion. The whole point of lead conversion to create Account so as to ensure the business is taking place with the customer. However, you can merge it with an existing account.

Please refer to the below links which might help you further with the above requirement.

https://salesforce.stackexchange.com/questions/4209/can-i-programmatically-merge-leads-to-existing-accounts

https://stackoverflow.com/questions/19984970/salesforce-apex-convert-leads-with-the-same-accountid-duplicate-id-in-list

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
James Roberts 32James Roberts 32
Thanks Khan. 
I'm looking at the second link and I can see that it need to use the following line to set the Account ID:

lc.setAccountId(accountMap.get(myLead.Company).id)

But when I try to use this I receive the error that Account Map does not exist. What do I need to add to my class to create the Account Map?