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
ColdfingerColdfinger 

Apex Trigger/addError prevents custom code insert

I have some code on the Lead Trigger which filters the lead coming in, and if certain details are true about it, instead of adding the lead to the system it will instead create a custom object that I have defined.

 

Now my trouble is, whenever I add the "addError" command to the lead coming in, to suppress it being added, the "insert" on my custom object fails

If I remove the addError, the custom object is added, but the lead is also added.

 

I would really like the lead not to be inserted, but the custom object to be inserted.

 

Here's some cut down code which should show the case in question:

 

trigger LeadNew on Lead (before insert) {

    for (Lead l:Trigger.new)
    {

/* condition met test generated*/

        if (bConditionMet)
        {
            LeadTask__c leadTask=new LeadTask__c();

/* create the leadtask from info in the bad lead */

            insert leadTask;


/* comment out the line below and the lead and leadtask are both added

if they're not commented out, then neither are added

*/

         l.addError('Lead not created as a task was generated instead');
        }
    }

}

 

Any suggestions would be gratefully received.

ShamSham

IMHO Instead of using statement insert LeadTask__c;

 

use the Database.insert(LeadTask__c,false);

 

 

ColdfingerColdfinger
Thanks for the suggestion, it doesn't make any difference though, the behaviour is the same as before (ie removing the addError it inserts both, adding the addError neither are inserted)
wesnoltewesnolte

Hey

 

That suggestion was almost correct. You need to use that syntax when inserting the lead though e.g. you have a visualforce page and the controller of this page inserts the lead, it's at this point that you need to specify

 

Database.insert(MyLeads,false);

 

Cheers,

Wes

ColdfingerColdfinger

Thanks for your recommendation.

 

The trouble with that is that these leads are being added by the salesforce WebToLead servlet.  Is there a way of changing the way those are added to the system?