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
Axel DuhêmeAxel Duhême 

Delete Trigger: Update records instead of Deleting them

Hi,

I'm trying to set up a trigger so that when a user deletes a contact, it is updated (with a True value in the Inactive__c checkbox) instead of being deleted.

The use case here is that when a user deletes a contact from their Outlook address book, I want it to remain in the database as inactive after Salesforce for Outlook / Lightning Sync triggers the delete.

Of course, I would include an excpetion in the trigger sor that User with the admin profile can properly delete records.

Hope someone can help!

Axel.
 
bretondevbretondev
I was not very optimistic but I found a way of doing that.
The algorithm is a bit weird but it works in my DE org.
The records get actually deleted , but the trigger undeletes them , and finally updates them with the flag.
Notice I had to use a @future method, because if you run all that synchronously, you stay in the original transaction and SF tells you that you cannot undelete a record that was just deleted

APex Trigger
 
trigger Test on Contact (after delete) {
	TestUndelete.updateDeleted(Trigger.oldMap);
}
Apex Class
 
public class TestUndelete {

    public static void updateDeleted(Map<Id,Object> mapOfIds) {
        
        //Converting map of IDs to list of IDs because Maps not supported by future methods
        List<Id> listOfIds =new List<Id>();
		listOfIds.addAll(mapOfIds.keySet());
        
        updateDeletedFuture(listOfIds);
    }
    
    
    @future
    public static void updateDeletedFuture(List<Id> listOfIds) {
        
        //Method receiving list of IDs because Maps not supported by future methods
        //Undeleting the records that were just deleted
        List<Contact> myList = [Select Id,Inactive__c FROM Contact WHERE Id IN :listOfIds ALL ROWS];
        undelete myList;
        
        //Flagging the records
        for (Contact c : myList) {
            c.Inactive__c = true;
        }
        
        //Finally updating the records to get them flagged
        update myList;

    }
    
    
}




 
Axel DuhêmeAxel Duhême
Thanks a lot for your help! I will be testing that in the morning and share my results. Best Regards, Axel Duh?me.