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
PSS_ITPSS_IT 

Delete Trigger

Hi,

 

I'd like to make a trigger that would delete a lead record when the lead first name and last name are the same.  Here is what I have so far and I'm getting error message:

 

Apex trigger Test1 caused an unexpected exception, contact your administrator: Test1: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.Test1: line 5, column 6

 

What do I need to change?

 

trigger Test1 on Lead (before insert) {
   for(Lead a: Trigger.new){
 if (a.firstname == a.lastname)
 try {
     delete a;
   } catch (DmlException e)
   {}
   }
  }

 

Thanks in advance!

Best Answer chosen by Admin (Salesforce Developers) 
MarkWaddleMarkWaddle

You cannot delete a row that does not yet exist. If you call the sObject.addError() function with a message that describes the error it will cause that row to not be inserted and the error message will be provided to the user or webservice client.

 

if ( ...) {

  a.addError('Leads cannot have matching first and last names.');

}

 

If you want it to fail silently you might try removing the item from the list. NOTE: I HAVE NOT TRIED THIS MYSELF NOR DO I KNOW IF IT WORKS, but it is worth a shot.

 

See http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_exceptions.htm for reference.

 

Regards,

Mark

All Answers

MarkWaddleMarkWaddle

You cannot delete a row that does not yet exist. If you call the sObject.addError() function with a message that describes the error it will cause that row to not be inserted and the error message will be provided to the user or webservice client.

 

if ( ...) {

  a.addError('Leads cannot have matching first and last names.');

}

 

If you want it to fail silently you might try removing the item from the list. NOTE: I HAVE NOT TRIED THIS MYSELF NOR DO I KNOW IF IT WORKS, but it is worth a shot.

 

See http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_exceptions.htm for reference.

 

Regards,

Mark

This was selected as the best answer
Ajay.DixitAjay.Dixit

If still you want to delete try trigger  after Insert then i guess you can delete. Other wise stated above is better option.

PSS_ITPSS_IT

Thanks Mark,  a.addError worked great!

 

Gregg