Development questions

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

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.');
        }
    }
}
apex-triggertriggercodingscenariosecurity