[SalesForce] Trigger to convert lead to existing Account

We have a system that feeds vetted Accounts into our Salesforce, but the process originates in the Salesforce Lead object.
Thus when approved, the Account is created by feed, so the Account will always exist before conversion.
So obviously I don't want to create another Account.
I do want to create a new Opportunity set it at the existing Account.
I'd like to add the converted as a Contact at the Account, too.

here's my start – I can convert, but not tell it to use the existing Account.

trigger LeadConverterNewInstitution on Account (after insert) {
    LeadStatus convertStatus = [
          select MasterLabel
          from LeadStatus
          where IsConverted = true
          limit 1
     ];

    List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
    List <id> AccLeadSubIds = new List <id>(); 

    for (Account NewAccount: Trigger.new){

      if (newAccount.SubmittedLeadID__c != ''){    

      AccLeadSubIds.add(newAccount.SubmittedLeadID__c);


      }

      List <lead> LeadsToConvert = [select id, Business_Line__c,  company, name from Lead where ID in: AccLeadSubIds and isConverted = false];

      for (Lead LTC : LeadsToConvert){

           Database.LeadConvert lc = new Database.LeadConvert(); 
          lc.setLeadId(LTC.Id);

          String oppName = LTC.Business_Line__c + ' ' + LTC.Company; 
          lc.setOpportunityName(oppName); 

          lc.setConvertedStatus(convertStatus.MasterLabel);

          database.LeadConvertResult lcr = Database.convertLead(lc); 
          System.assert(lcr.isSuccess());

      }
   }
}

Best Answer

You can create map of populate in your Trigger.new loop storing the lead Ids (your custom submittedLeadId__c field) as the key, and the corresponding account Id as the value. Then inside your lead convert loop, use this map to fill in the setAccountId method on your Database.LeadCovert object, something like lc.setAccountId(acctIdsMap.get(LTC.Id));

Related Topic