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
Abhilash Mishra 13Abhilash Mishra 13 

Auto converting lead with trigger

Hi guys, I have been trying to write a trigger to convert lead if someone changes its status to closed converted the code is:
trigger convertlead on Lead ( after update ,after insert) {

list<lead> mylead= trigger.new;
for(lead l : mylead)
{
    if(l.status=='Closed - Converted')
    {
      
   
        Database.LeadConvert lc = new Database.LeadConvert();
    
    lc.setConvertedStatus('Closed - Converted');
    lc.setLeadId(l.id);



Database.LeadConvertResult lcr = Database.convertLead(lc);
System.debug(lcr.isSuccess());
  } 
}
}
its giving follwoing error:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger WkAbhi.convertlead caused an unexpected exception, contact your administrator: WkAbhi.convertlead: execution of AfterUpdate caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, System.DmlException: Update failed. First exception on row 0 with id 00Q28000001ovz7EAA; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, WkAbhi.convertlead: execution of AfterUpdate caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: [] Trigger.WkAbhi.convertlead: line 17, column 1: [] (System Code) : []: Trigger.WkAbhi.convertlead: line 17, column 1


Please help....
Vijay NagarathinamVijay Nagarathinam
Hi  Abhilash,

Try the following code it will be work.
 
trigger autoLeadConversion on Lead (after insert) {
 
LeadStatus convertStatus = [Select MasterLabel from LeadStatus where IsConverted = true limit 1];
 
List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
for (Lead lead: Trigger.new) {
if (!lead.isConverted && lead.Status == 'Open' ) {
Database.LeadConvert lc = new Database.LeadConvert();
String opportunityName = lead.Name;
 
lc.setLeadId(lead.Id);
//lc.setAccountId(AccountId); // you can set the AccountId instead of create a <span id="IL_AD2" class="IL_AD">new account</span> and contact is created the <span id="IL_AD6" class="IL_AD">mention</span> account
lc.setSendNotificationEmail(false);
lc.setOpportunityName(opportunityName);
//lc.setDoNotCreateOpportunity(true); // <span id="IL_AD8" class="IL_AD">Optional</span> to create a Opportunity
lc.setConvertedStatus(convertStatus.MasterLabel);
leadConverts.add(lc);
}
}
if (!leadConverts.isEmpty()) {
List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
}
}
Let me know if you need any help regarding this.

Thanks,
Vijay
 
Abhilash Mishra 13Abhilash Mishra 13
i have used that before but i want to call trigger when some one update the status to closed converted instead of converting the lead through covert button.
srinu vassrinu vas
Hi,
Abhilash Mishra 13
your code is absolutely fine,
I'm assuming that this also included an error Id? If so, your only real option is to reach out to Salesforce support with the error id. Typically this type of thing will happen if there is a problem with the back end schema or something similar.
Tara HamondTara Hamond
Abhilash, I ran into a similar issue and the problem was that the lead is updated as part of the conversion, so the trigger gets fired a second time. Change 
if(l.status=='Closed - Converted')

to
if(l.status=='Closed - Converted' && !l.isConverted)
to prevent it from attempting to convert the lead a second time.
 
JAKIR MOMINJAKIR MOMIN
Hi Vijay Nagarathinam,

Thanks 

I have tried autoLeadConversion and it is working fine.  My query is, i have created one custome field "Account Manager" (lookup relation with user) on Lead object. When AutoLeadConversion trigger will run then New Opportunity, New Account and Contact is creating after that I want "Account Manager" (User Lookup) field Update (SetOwnerId) as a Owner of New Opportunity, New Account & New Contact. 

Can you help me ?
Final testFinal test
Hello Abhilash Mishra

I have tried autoLeadConversion (Account and Contact)  When Status is Closed-Converted:
Class:
public class LeadConversionHandler {

    public void leadConversionMethod(List<Lead> lstLead) {
        
        List<Contact> lstContact = new List<Contact>();
        List<Account> lstAccount = new List<Account>();
        system.debug('Trigger Content '+lstLead);
        
        if(!lstLead.isEmpty()) {
            
            for(Lead objLead :lstLead) {
                
                if(objLead.Status == 'Closed - Converted') {
                    
                    Account objAccount = new Account();
                    objAccount.Name = objLead.Company;
                    lstAccount.add(objAccount);
                    
                    Contact objContact = new Contact();
                    objContact.FirstName = objLead.FirstName;
                    objContact.LastName = objLead.LastName;
                   // objContact.AccountId = objLead.ConvertedAccountId;
                    objContact.Email = objLead.Email;
                    lstContact.add(objContact);
                    system.debug('Contact Object '+objContact);
                }
            }
            insert lstContact;
            insert lstAccount;
            system.debug('List of Contact '+lstContact);
        }
        

        
    }
}

Trigger:
trigger LeadConversionTrigger on Lead (After insert,After update) {
    
    system.debug('In Trigger');
    LeadConversionHandler objLeadConversionHandler = new LeadConversionHandler();
    objLeadConversionHandler.leadConversionMethod(Trigger.new);

}

If it is helping you then please mark as best.