[SalesForce] Use addError method and make a DML operation

The problem that I am having is that I am using addError method in before insert trigger which actually rollback every DML I make including @future method calls, sending email, queueing batch jobs, or performing any DML. What I would like to know is
how to stop the process of converting Lead to Account and at the same time dispaly message in the convert page as well as to set and update a custom Lead status field to 'Existing Deal'.

To be more precise what I need to acheve:
1. Stop the process of converting Lead to Account.
2. Display message in the convert Lead to Account page that the respective Lead is not converted.
3. Set and Update the Lead.Status__c field to 'Existing Deal'.

Apparently this can't be achieved by using the addError method and I will strongly appreciate if you can advise how to proceed and find a solution to this issue?

Regards,

Dilyan

Best Answer

You can't have it both ways. Using addError removes all side effects of the transaction, including sending emails, kicking off batch/scheduled/future calls, and committing data that was otherwise created during the trigger's life cycle. If you want to prevent conversion in some circumstances, you can override the lead convert button with a custom Visualforce page, and enforce the logic there. Simply perform your logic of checking before conversion, display error if appropriate and update lead, or convert lead and redirect to opportunity page. The override is located in Setup > Customize > Leads > Buttons, Links, and Actions.

Example Controller (conversion only)

public class LeadConvert {
    Lead record;
    ApexPages.StandardController c;
    public LeadConvert(ApexPages.StandardController controller) {
        record = (Lead)controller.getRecord();
        c = controller;
    }
    public PageReference convertLeadRecord() {
        Database.LeadConvert lc = new Database.LeadConvert();
        lc.setLeadId(record.Id);
        lc.setOpportunityName('Default Name');
        try {
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            return new ApexPages.StandardController(new Opportunity(Id=lcr.getOpportunityId())).view();
        } catch(Exception e) {
            record.Status__c = 'Existing Deal';
            return c.save();
        }
    }
}

Example Page (conversion only)

<apex:page standardController="Lead" extensions="LeadConvert" action="{!convertLeadRecord}">

</apex:page>

Obviously, if you want something more complicated, like the actual UI presented on conversion out of the box, you'll have to build the entire thing yourself. Such an effort is outside the scope of this question, as it would require several hundred lines of code for a full implementation.

Useful Documentation:

Related Topic