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
vishal yadav 86vishal yadav 86 

Trigger to convert lead

I want to write a trigger to convert lead after updating the status field to "working-contacted".
Review the errors on this page.
VishalYadav.LeadTrigger: execution of AfterUpdate caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, convertedStatus is required.: [Status] Trigger.VishalYadav.LeadTrigger: line 8, column 1

TRIGGER:
----------
Trigger LeadTrigger on Lead (after update) {
    For(Lead l: Trigger.new)
    {
        if(l.IsConverted == false)
        {
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(l.id);
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            System.assert(lcr.isSuccess());
        } }
}
Arvind_SinghArvind_Singh
Hello Vishal 

It need some more work on trigger part to acihive it optimized way Look at below code 

Some time back I was working on one similar requirement below post helped me built very optimized solution. 

https://blog.deadlypenguin.com/2014/07/23/intro-to-apex-auto-converting-leads-in-a-trigger/
https://blog.jeffdouglas.com/2009/02/13/enhancing-the-lead-convert-process-in-salesforce/
 
trigger AutoConverter 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 == 'working-contacted') {  // Check status here or change as per req
               Database.LeadConvert lc = new Database.LeadConvert();
               String oppName = lead.Name;

               lc.setLeadId(lead.Id);
               lc.setOpportunityName(oppName);
               lc.setConvertedStatus(convertStatus.MasterLabel);

               leadConverts.add(lc);
          }
     }

     if (!leadConverts.isEmpty()) {
          List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
     }
}

Hope it help. 



 
vishal yadav 86vishal yadav 86
Thanks,
Arvind_Singh.