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. – Martin Lezer Jul 10 '17 at 8:50

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');                       


| improve this answer | |
  • No @Alexander Berehovskiy I am getting errors while running the unit test case – Kronos Jul 10 '17 at 9:18
  • what error do you have? – Oleksandr Berehovskyi Jul 10 '17 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 Jul 10 '17 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 Jul 10 '17 at 10:00
  • 1
    @Eric yes... Advice for me from me - Don't answer questions while tired :) – Oleksandr Berehovskyi Jul 10 '17 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.