0

We have accounts OWD set to Private and OWD for Activities set as Controlled by Parent but people can still delete their activities on the Account for example if a call doesn't go well.

How can I prevent them from doing so?

3

A trigger that fires before delete can put an error on those records if they meet desired criteria.

trigger PreventDelete on Event (before delete) {
    if(UserInfo.getUserId() != "##justforexampleincaseyouwanttobeabletodelete###"){
        for (Event e : Trigger.old) {
            e.addError('Unable to delete record!');
        }
    }
}
  • 1
    +1 But I'd use a Custom Permission these days. After all, admins come and go, but permissions are forever. – sfdcfox Jan 23 '18 at 21:09
  • @sfdcfox Permission Sets are a pain to check in Apex compared to Hierarchy Custom Settings. – Adrian Larson Jan 23 '18 at 21:10
4

You can use an Apex Trigger which leverages the SObject.addError method. You should look into trigger best practices such as handlers, service/domain layer, etc, but the basic idea would look like:

trigger Event on Event (before delete)
{
    for (Event record : trigger.old)
    {
        record.addError('Customize this message');
    }
}

One note, it's good to build some sort of bypass to this functionality, as you may want to occasionally delete records as an admin or some such. You can use a Hierarchy Custom Setting to do so:

trigger Event on Event (before delete)
{
    if (ActivityTrigger__c.getInstance().preventDelete())
    {
        ActivityService.addError(trigger.old, 'Some error message');
        // you would have to actually implement an Activity Service layer
        // the addError method would just loop through the provided records
        // and add the error string to each
    }
}
  • 4
    Did you see the new FeatureManagement class? A Custom Permission is now even easier to use: if(!FeatureManagement.checkPermission('CanDeleteTask')) {... – sfdcfox Jan 23 '18 at 21:10
  • 1
    Wha? That looks specific to package development? Well looks like I can scrap a utility class now. Sweet. – Adrian Larson Jan 23 '18 at 21:10
  • Found out about this this morning, tested in my sandbox, and it works outside of packages, too. – sfdcfox Jan 23 '18 at 21:16
3

If you want to do this declaratively, turn off the Delete permission for those users' profiles. Separate answer because totally separate approach.

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.