I want my trigger to prevent deletion of Account records, the code doesn't show any error but my Account records are still being deleted? here is my code

trigger PreventAccountDelete on Account(before delete){
    for(Account a :[select Id from Account where Id IN:Trigger.old])
        System.debug('Cant delete');

  • 2
    You're not doing anything in your code. Commented Jul 10, 2017 at 8:50

1 Answer 1


In order to prevent delete transaction to be committed to DB, you need to addError to record, that should not be deleted

trigger PreventAccountDelete on Account (before delete) {

    for(Account acc : trigger.old){
        acc.addError('Account Cannot be deleted');

to test this behavior run the following unit-test

private class PreventAccountDeleteTest {

    static void testPreventAccDel(){
        Account accRecord = new Account(name='testAccount');
        insert accRecord;


            delete accRecord;
            System.assertEquals(false, 'An Error was expected');
        }catch(DMLexception e){
            System.assertEquals(true, e.getMessage().contains('Account Cannot be deleted'),'Account Cannot be deleted');                       


  • No @Alexander Berehovskiy I am getting errors while running the unit test case
    – Kronos
    Commented Jul 10, 2017 at 9:18
  • what error do you have? Commented Jul 10, 2017 at 9:37
  • I actually corrected the problem of another Trigger firing on my intended object but now there is this strange behavior exhibited by my trigger.
    – Kronos
    Commented Jul 10, 2017 at 9:58
  • When i use the addError method in place of my System.debug there is a validation error which prevents the record from being deleted, but when i use the System.debug method the record still gets deleted.
    – Kronos
    Commented Jul 10, 2017 at 10:00
  • 1
    @Eric yes... Advice for me from me - Don't answer questions while tired :) Commented Jul 10, 2017 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .