You need to sign in to do that
Don't have an account?
Khan Anas
How to write Before Delete Trigger to restrict deletion
I am new to Salesforce, please help me. I have custom object Book__c with name and price__c fields. I need to write a trigger that restricts deletion of a book which is the costliest.
Below is my code:
When I am deleting Costliest book it is working fine. But when I am trying to delete other books, it is showing following error:
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger Book_Del_trg caused an unexpected exception, contact your administrator: Book_Del_trg: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Book_Del_trg: line 7, column 1".
Any suggestions please? Thanks in advance.
Below is my code:
Trigger Book_Del_trg on Book__c (before delete) { List <Book__c> bag = trigger.old; bag = [select id, price__c from Book__c order by price__c desc limit 1]; for (Book__c book : bag){ if(book.id != null){ Book__c b = Trigger.oldMap.get(book.Id); b.addError('Cannot delete costliest book'); } } }
When I am deleting Costliest book it is working fine. But when I am trying to delete other books, it is showing following error:
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger Book_Del_trg caused an unexpected exception, contact your administrator: Book_Del_trg: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Book_Del_trg: line 7, column 1".
Any suggestions please? Thanks in advance.
Mark it best if it helps you
Regards
Suraj
All Answers
Mark it best if it helps you
Regards
Suraj
Let us know if this will help you