function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JonSimmonsJonSimmons 

Cancel Delete in Trigger

I would like to create a Trigger that captures a user's attempt to delete a record and instead mark that record as "Inactive" and cancel the delete request.
 
I have attempted to use the beforeDelete and afterDelete triggers, as well as attempted to allow the delete and then undelete the record afterwards.  I keep running into various walls.
 
I imagine that this is something that is probably fairly common yet I can't find any examples of how best to do this. 
Can anyone give me some ideas or otherwise point me in the right direction?
 
 
Thanks
Jon
 
ajitvermaajitverma
Hi Jon,

we can do one thing here, i hope u have tried this.
inside beforeDelete event you can use addError function to add the error
message to that particular object. so once the error is added record will not be
deleted.
suppose you are dealing with the account object.so inside you trigger add this code
<object of account>.addError('<give error message here>');


this way you can prevent the deletion.



JonSimmonsJonSimmons
Hi,
 
Thanks for the suggestion.  I have tried raising an error, which will cancel the delete, but the customer would like the change to be seamless, they don't want the usere to know that they have not deleted the record. 
So if at all possible it should act as if it has deleted the record but instead simply uncheck and Active checkbox instead.
 
This is why I was thinking of using Undelete in the afterDelete trigger but have run into some issues there as well.
 
Thanks
Jon
 
 
wintamutewintamute
You can always override the delete button and use your own logic instead. So you can do manual checking or whatever your usecase is. You can also avoid deletion altogether and just set the record invalid like you want to do.

Unfortunately, with override you cannot call apex directly, so you have to use either a scontrol or a visualforce page. If you don't want to use visualforce, the scontrol can call your apex webservice or do the field update itself.

This approach avoids the trigger altogether, so it works only by clicking on the delete button by the user, not when used via the dataloader and so on (see documentation for details on button overrides).
JonSimmonsJonSimmons

 

Hi,

 

Thanks for the suggestions.  I was actually able to accomplish this by using Undelete in the After Delete trigger. 

I was running into trouble because I couldn't pass a Trigger.old or Trigger.new record to undelete and I couldn't locate the record I wanted with a select because it was deleted.  Of course I found the ALL ROWS directive for SELECT and was able to locate the deleted record and undelete it.   Problem solved.

 

Thanks

Jon