Deleting a record from its own update trigger


Here’s a nice little one a colleague and I stumbled on today – we had a requirement where we needed to delete an Event if the Event’s status was updated to a specific value.

Going at a deletion the “usual way”, the trigger barked at us that we couldn’t do any DML on the triggered records themselves…so voila, here we go:

if(trigger.isUpdate) {

List<Event> lstEventsToDelete = new List<Event>();

for(Event e : trigger.new) {
Event eDel = new Event(Id=e.Id);
lstEventsToDelete.add(eDel);
}

delete lstEventsToDelete;

}

Nice little “workaround” for deleting the same record you’re triggering on.  =)

Advertisements

12 thoughts on “Deleting a record from its own update trigger

  1. Worked great, needed to convert a campaign member from a lead to a contact in a trigger and this did the job, thanks.

  2. New Lead -> Search for Company and Last Name

    if it already exists in SF, then

    copy the new Lead Phone Number – > Old Lead Phone, only if the old Lead phone number is blank.

    and delete the New Lead.

    Hi can u help with the above requirement

  3. Hi

    Also tried this on an OppLineItem and got a error: First exception on row 0 with id 00kW0000003TkwdIAC; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00kW0000003Tkwd) is currently in trigger OpportunityLineItemDowngrade, therefore it cannot recursively delete itself: []: Trigger.OpportunityLineItemDowngrade: line 87, column 1

  4. Awesome, we were looking for a solution to delete the product from cart on zero quantity. It is working now…
    Thanks

  5. Thanks Andrew I tried your solution on an After Update trigger but not for deleting a record… Only for doing an update within an update trigger: For example if someone wants to update the Billing address for a Person account then the Mailing address should auto-update. Same for shipping Address to Physical updates. It all seems to be working quite nicely. Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s