+ Start a Discussion
Mahadev Wagalgave 9Mahadev Wagalgave 9 

Deleting a record from its own update trigger

I have a requirement where I need to delete a contact record based on some conditions while updating the same Contact record.

How can we delete a record from its own update trigger ?
Neetu_BansalNeetu_Bansal
Hi,

You can create a checkbox field on Contact and as soon as your conditions met, check that field. Later you can write a batch process to delete all those Contact records whose checkbox is checked.

Thanks,
Neetu
shikher goelshikher goel
Hi Mahadev,

You can do that in after update trigger. In that trigger store the Current contact id's into list and then fetch those records from the database once again and perform the delete operation on the database fetched records.

See the small code : If you have any contact whose already last name as "MYLASTNAME" and try to update that contact. That contact will be deleted.
trigger DeleteContact on Contact (after update) {
 List<Id> contactIdlist = new List<Id>();
 for(COntact c:Trigger.new)
    {
     if(c.lastName == 'MYLASTNAME')
        contactIdlist.add(c.id);
    }

 List<Contact> listOfContact = [select id from contact where id = :contactIdlist];
 delete listOfContact ;
}  

Let me know if this works.

Thanks,
Shikher Goel
Mahadev Wagalgave 9Mahadev Wagalgave 9
Thank you Neetu and Shikher .

@Shikher, Yes the code worked, we can optimize it more by removing the SOQL. We can directly write delete contactIdlist.

@Neetu, we can use your solution, if we have a requirement to delete the records in before update trigger.

Please let me know, if you have any queries. 

Regards,
Mahadev