+ Start a Discussion
Avinash RaviAvinash Ravi 

Help to Understand

Can someone help me understand this piece of code? I'm still a newbie and any help on the flow would be greatly appreciated
 
trigger AptsActivityHistoryTrigger on Task (before delete, before update) {
    String ERROR_MESSAGE = 'Update/Delete of Activity History entries are not permitted';
    String PROFILE_SYS_ADMIN = 'System Administrator';
    Id sysAdminProfileId=null;
    // Bulk processing NOT supported
    if (Trigger.size != 1) {
        return;
    } 
    //applicable for update and deletes only
    if (Trigger.isBefore) {
        if ((Trigger.isUpdate) || (Trigger.isDelete)) {
            Task taskObj = [select Id, whatId, status from Task where Id = :Trigger.old[0].Id];
            
            // parent is an agreement?
            List <Apttus__APTS_Agreement__c> agmts = [select Id from Apttus__APTS_Agreement__c where Id = :taskObj.whatId];

            // sys admin profile id
            List<Profile> profileList = [select Id, Name 
                            from Profile
                            where Name = :PROFILE_SYS_ADMIN];
                            
            if ((profileList != null) && (!profileList.isEmpty())) {    
                sysAdminProfileId = profileList[0].Id;
            }   

            if (agmts == null || agmts.size()<=0 || taskObj.Status != 'Completed' || sysAdminProfileId == UserInfo.getProfileId() ) {
                return;
            }
            
            //error to indicate action is not permitted
            String errMsg = ERROR_MESSAGE;            
            if (Trigger.isUpdate) {
                Trigger.new[0].addError(errMsg);
            } else {
                Trigger.old[0].addError(errMsg);
            }
        }       
    }
    return;

}
James LoghryJames Loghry
It's a poorly written trigger that attempts to prevent updates and deletes of tasks associated with apptus__APTS_Agreement__c records, if the user modifying or deleting is not a Sys admin.  However, if there's a bulk update, the trigger is ignored and task updates and deletes are allowed.