# Write a trigger on Task so that only the Account Owner or a System Administrator can delete a Task related to an Account (WhatId).

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Accenture, Deloitte, Capgemini · **Tags:** apex-trigger, trigger, coding, scenario, security

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-on-task-so-that-only-the-account-owner-or-a-system-administrator-can-delete-a-task-related-to

## Answer

Use `before delete` on Task. For Tasks whose `WhatId` is an Account, allow only the Account Owner or a System Administrator.

```apex
trigger TaskTrigger on Task (before delete) {
    Set<Id> accIds = new Set<Id>();
    for (Task t : Trigger.old) if (t.WhatId != null && t.WhatId.getSObjectType() == Account.SObjectType) accIds.add(t.WhatId);
    if (accIds.isEmpty()) return;
    Map<Id, Account> accs = new Map<Id, Account>([SELECT Id, OwnerId FROM Account WHERE Id IN :accIds]);
    Boolean isAdmin = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()].Name == 'System Administrator';
    for (Task t : Trigger.old) {
        if (accs.containsKey(t.WhatId) && !isAdmin && accs.get(t.WhatId).OwnerId != UserInfo.getUserId()) {
            t.addError('Only the Account Owner or a System Administrator can delete this Task.');
        }
    }
}
```

---
Source: ForceChallenges · last updated 2026-10-19
