You need to sign in to do that
Don't have an account?
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!
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
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
If still you want to delete try trigger after Insert then i guess you can delete. Other wise stated above is better option.
Thanks Mark, a.addError worked great!
Gregg