+ Start a Discussion
Tom CaesarTom Caesar 

Update field in opportunity on task completion

A custom field named Calls_Made__c is numeric and increments by 1 each time an outgoing call task is completed.

This happens in two areas, on the Lead and on the Account (opportunity) - (seperate counts for each)

The Lead update works fine, but am having trouble with the acount count incrementing on the opportunity task completion.
trigger UpdateLeadOpenTasks on Task (after delete, after insert, after undelete, after update) {
System.Debug('Runnning UpdateLeadOpenTasks');
// Declare the variables
public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();
public set<Id> AccountIDs = new Set<Id>();
public list<Account> AccountsToUpdate = new List<Account>();
// Build the list of Leads and Accounts to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
System.Debug('Creating a list of IDs to update');
    for(Task t: Trigger.new){       
        if(t.WhoId !=null) {
        //We need to put something here to handle a fail if the user doesn't link an activity to a Account or Lead

            if(string.valueof(t.WhoId).startsWith('003')) {
                // nothing with contact
                System.Debug('No Task WhoID set for Contact');
            } else if(string.valueof(t.WhoId).startsWith('00Q')) {
            } else {

        else {
        System.Debug('No Task WhoID set');
    } //end for
    for(Task t: Trigger.old){
            // leads
         }else if(string.valueOf(t.WhoId).startsWith('003')){
            // nothing for contact
            System.Debug('No Task Trigger set for Contacts'); 
        } else {
            // account
// Update the Leads
   System.Debug('Lead has at least 1 record - doing something');
   for(Lead l: [Select l.Id, l.Calls_Made__c,
   (Select Id From Tasks where CallType='Outbound' and Status='Completed') //Change   select statement to just be NVM Tasks
   From Lead l where Id in :LeadIDs])
   LeadsToUpdate.add(new Lead(Id=l.Id, Calls_Made__c = l.Tasks.size()));
   update LeadsToUpdate;
// Update the Accounts
System.Debug('Account has at least 1 record - doing something');
//We need to put in code to handle it if we don't know who the Account is
for(Account c: [Select c.Id, c.Calls_Made__c,
(Select Id From Tasks where CallType='Outbound' and Status='Completed')//Change select statement to just be NVM Tasks
From Account c where Id in :AccountIDs])
AccountsToUpdate.add(new Account(Id=c.Id, Calls_Made__c = c.Tasks.size()));
update AccountsToUpdate;

The Account side doesn't work because AccountId on task isn't store in the WhoId. It is stored in the WhatId. So line 30 will never give you actual AccountIds and line 73 will always be null. If you check the WhatId of the taks for startsWith('001'), you will get a list of Accounts and your trigger should work.