0

I am running into cpu limit with this am I am missing somthing? And also how can I adjust the code to avoid harcoding the ID like i did.

      Trigger AutoConverter on Lead (after insert,after update) {
     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 ) {
               Database.LeadConvert lc = new Database.LeadConvert();

               lc.setLeadId(lead.Id);
               lc.setDoNotCreateOpportunity(TRUE); 
               lc.setConvertedStatus(convertStatus.MasterLabel);

                String leadOwner = lead.OwnerId;
              if(leadOwner.startsWith('00G')){
               Lc.OwnerId = '00535000001ZOZN'; }
               leadConverts.add(lc);
          }
     }

     if (!leadConverts.isEmpty()) {
          List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
     }
}
  • 2
    To not hard code the OwnerID you would have to soql the user like this - User u = [SELECT Id, IsActive FROM User WHERE username = 'some username']; – CodeMonger Feb 12 '20 at 15:44
  • 3
    This code, in isolation, doesn't look to be an issue in terms of CPU usage. The CPU limit is measured over the entire transaction (which includes this conversion, any triggers that run as a result of the Account/Contact/Opportunity generated by the conversion, etc...). Rooting out a CPU issue usually takes a fair bit of effort and diving into log files to see where the problem areas are. – Derek F Feb 12 '20 at 15:47
  • Non related to the question but you don't need the !leadConvers.isEmpty() line as stated on this question

    https://salesforce.stackexchange.com/questions/19399/any-reason-to-skip-dml-on-empty-lists

    – Alexander Aeons Torn Feb 12 '20 at 16:56
  • 1
    You can save yourself a query against your SOQL count and avoid hardcoding the OwnerId by storing the default owner in a custom metadata type. Additionally, Database.convertLead() only accepts a list of Database.LeadConvert() up to 100, whereas your trigger could process batches of up to 200. You'll need to account for that discrepancy in your code to avoid errors caused by bulk insert/update actions. – Todd Sprinkel Feb 12 '20 at 17:26

0 Answers0