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
Kevin Charette 8Kevin Charette 8 

autocoverting leads on lead field update

When a lead is updated (i'm thinking process builder here) i would like the lead to convert into a contact,account and trigger a flow I have already built to create an opp. 

I have a related account field that is a lookup(Account) field on the lead. If the account field is not null I would want the lead to convert into that account and then if it is null to create a new Account. 

Opp should not be created on conversion, it should be created off of the flow.

I'm assuming this has to be done using Apex. Any help here would be greatly appreciated!
Waqar Hussain SFWaqar Hussain SF
Hi Kevin,
Your requirement can be accomplish by apex trigger. I am assuming you want to aut convert lead, based on some criteria.
Let suppose you want to auto convert lead when the lead status is set to qualifie.
 
trigger AutoConvertLeads on Lead (after insert, after update) {
    
    LeadStatus CLeadStatus= [SELECT Id,ApiName, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
    List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
    for(lead l : trigger.new){
        if(l.Status == 'Qualified' && l.isConverted == false){
    
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
            Leadconvert.setLeadId(l.Id);
            if(l.Account__c != null)
            Leadconvert.setAccountId(l.Account__c);
            Leadconvert.setDoNotCreateOpportunity(true);
            Leadconvert.setConvertedStatus(CLeadStatus.ApiName);
            MassLeadconvert.add(Leadconvert);
            
        }
    }
    
    if (!MassLeadconvert.isEmpty()) {
        List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
    }
}