APEX Trigger and Test Class to Prevent Account Deletion | #Salesforce Tutorials



In this article you will learn to create a Before Delete Trigger and Test Class to prevent Account deletion based on a field's value condition.

Please follow below code : 

Trigger
1
2
3
4
5
6
7
8
trigger beforeAccDeletion on Account (before delete) {
    for(Account acc : trigger.old){
        if(acc.myField__c != null){
            acc.adderror('Can not delete the Account if myField is available');
        }
    }

}

Test Class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@isTest
private class beforeAccDeletionTest {
    static testmethod void testAccDelete(){
        Account acc = new Account();
        acc.Name='Acc1';
        acc.myField__c='AnyValue';
        insert acc;
        try{
            delete acc;
        }catch(DMLexception e){
            system.assert(e.getMessage().contains('Can not delete the Account if myField is available'),'Can not delete the Account if myField is available');                       
        }
    }
}

Check other posts as well !


If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 


Post a Comment

0 Comments