+ Start a Discussion
SFWesSFWes 

Task Trigger Help

Hi. I'm writing a Trigger for the Task object and I'm not sure if the code below is the most efficient way of achieving the result I need. The code works, but I want to see if it can be more efficient. I'm also just learning how to use Maps, which is a bit confusing right now for me.

 

This Trigger fires on Update / Insert and will set a checkbox to True on the Task object if the owner matches the Account Owner. If they don't match, then it will be set to False.

 

Any advise would be appreciated.

 

trigger TaskTest on Task (after insert, after update) {
	
	List<Task> tasks = new List<Task>(); //Tasks to Update
	Map<Id, Task> taskMap = new Map<Id, Task>();//Task & Opportunity Mapping
    Map<id, id> oppAccMap = new Map<id, id>(); //Account & Opportunity Mapping
    Map<Account, Task> accTaskMap = new Map<Account, Task>(); //Account & Task Mapping
	//Id rtTaskID = [select Id from RecordType where DeveloperName = 'Standard Task' and SObjectType = 'Task' limit 1].Id;
    
    
    //Loop through the Trigger
	for(Task tsk : Trigger.new){
        //This code should only apply to one Task Record Type
        //if(tsk.RecordTypeId == rtTaskId && tsk.WhatId != null && string.valueOf(tsk.WhatId).startsWith('006')){

            if(Trigger.isInsert ){ 
                taskMap.put(tsk.WhatId, tsk); //Add to Mapping
            }
            else if (Trigger.isUpdate){
                if(Trigger.oldMap.get(tsk.id).ownerId != tsk.ownerid || Trigger.oldMap.get(tsk.id).WhatId != tsk.WhatId)
                    taskMap.put(tsk.WhatId, tsk); //Add to Mapping
            }
    	//}
	}
	
    //Only move forward if the taskMap has values
    if(taskMap.size() > 0){
    
        //Map AccountID with OpportunityID
        for(Opportunity opp : [select Id, AccountId from Opportunity where Id in : taskMap.keySet()]){
            oppAccMap.put(opp.AccountId, opp.Id); //Add the AcountID and OpportunityId to the Map
        }
    
        //Map Account to Task
        for(Account acc : [select id, Name, OwnerId from Account where Id in : oppAccMap.keySet()]){
            accTaskMap.put(acc, taskMap.get(oppAccMap.get(acc.id)));	
        }
    
        for(Account accTmp : accTaskMap.keySet()){
            //Assume the Owners don't match
            Boolean isMatch = false;
            //Check if Account owner and Task owner match
            if (accTmp.OwnerId == ((Task)accTaskMap.get(accTmp)).OwnerId){
                isMatch = True;
            }

            tasks.add(new Task(id = accTaskMap.get(accTmp).id, Task_and_Account_Owner_Match__c = isMatch));
        }
        
        //Proceed with update if tasks size is greater then 0
        if (tasks.size() > 0){
            update tasks;
        }
    
    }
 
}