[SalesForce] Convert Lead on Update trigger

anybody know how to convert a lead on update? It is for if the lead Email matches an existing Contact's email. I can get it to work on after insert, but when I try on update(before update or after update) I get this error:

Error: Invalid Data. Review all error messages below to correct your
data. Apex trigger 'leadFilter' caused an unexpected exception,
contact your administrator: leadFilter: execution of BeforeUpdate
caused by: System.DmlException: ConvertLead failed. First exception on
row 0; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id =
00QR000000DGrtr) is currently in trigger leadFilterTrg, therefore it
cannot recursively convert itself: []: Class.leadFilter.filterLeads:
line 76, column 1

Class is like this:

for (Lead l : leadRecords){                                 
            if(contactEmailMap.containsKey(l.email)){
                system.debug('contactMap contains lead email: ' + l.email);
                Contact c = contactEmailMap.get(l.email);

            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setLeadId(l.id);
            lc.setContactId(c.id);
            lc.setAccountId(c.accountId);
            lc.setDoNotCreateOpportunity(true);
            lc.setOwnerId(c.ownerId);
            lc.isSendNotificationEmail();
            lc.setConvertedStatus('Duplicate Lead');                    
            convertList.add(lc);                                            
        }

    }
    database.convertLead(convertList);

Best Answer

Convert it in a future method. You can only involve in record in a trigger in a single instance of an event. For example, an insert can recursively call an update, which can recursively call a delete. However, a convert is considered an update, so you can't call a convert in an update trigger. You'll need to convert it asynchronously, via a future method.

Related Topic