function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
StevekBlueSnapStevekBlueSnap 

Edit for Lead Activity Counter

I have tried simplistically to swap Lead everywhere I see Opportunity or opp. This method does not work. What would I have to edit to establish the activity counter on Leads?

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
trigger TaskUpdateOpportunity on Task (after delete, after insert, after undelete, after update) {

    Set<ID> oppIds = new Set<ID>();
    //We only care about tasks linked to opportunities.
    String prefix =  OpportunityActivityCount.oppPrefix;

    //Add any opportunity ids coming from the new data
    if (Trigger.new != null) {
        for (Task t : Trigger.new) {
            if (t.WhatId != null && String.valueOf(t.whatId).startsWith(prefix) ) {
                oppIds.add(t.whatId);
            }
        }
    }

    //Also add any opportunity ids coming from the old data (deletes, moving an activity from one opportunity to another)
    if (Trigger.old != null) {
        for (Task t : Trigger.old) {
            if (t.WhatId != null && String.valueOf(t.whatId).startsWith(prefix) ) {
                oppIds.add(t.whatId);
            }
        }
    }

    if (oppIds.size() > 0)
        OpportunityActivityCount.updateOpportunityCounts(oppIds);

}

 

public with sharing class OpportunityActivityCount {

    public static Boolean didRun = false;
    public static String oppPrefix =  Opportunity.sObjectType.getDescribe().getKeyPrefix();

    /*
    * Takes a set of opportunity IDs, queries those opportunities, and updates the activity count if appropriate
    */
    public static void updateOpportunityCounts(Set<ID> oppIds) {

        if (didRun == false) { //We only want this operation to run once per transaction.
            didRun = true;

            //Query all the opportunites, including the tasks child relationships
            List<Opportunity> opps = [SELECT ID, activity_count__c, (SELECT ID FROM Tasks), (SELECT ID FROM Events) FROM Opportunity WHERE ID IN :oppIds];
            List<Opportunity> updateOpps = new List<Opportunity>();

            for (Opportunity o : opps) {
                Integer count = o.tasks.size() + o.events.size();

                if (o.activity_count__c != count) {
                    o.activity_count__c = count;
                    updateOpps.add(o); //we're only doing updates to opps that have changed...no need to modify the others
                }
            }

            //Update the appropriate opportunities
            try {
                update updateOpps;
            } catch (Exception e) {
                //This is controversial. Anything could happen when updating the opportunity..validation rule, security, etc. The key is we don't
                //want the event update to fail...so we put a try catch around the opp update to make sure we don't stop that from happening.
            }
        }
    }

    /*
    * Test method for this class and TaskUpdateOpportunity and EventUpdateOpportunity
    */
    public static testMethod void testCountTask() {
        //Setup
        Account a = new Account(name='Test');
        insert a;

        Opportunity opp = new Opportunity(accountId = a.id, name='Test Opp', StageName='New', CloseDate=System.today());
        insert opp;

        //Insert our first task
        Task t = new Task(subject='Test Activity', whatId = opp.id);
        insert t;

        //Verify count
        opp = [SELECT ID, activity_count__c FROM Opportunity WHERE ID = :opp.id];
        System.assertEquals(1,opp.activity_count__c);

        //Disconnect task from the opportunity
        didRun = false; //Reset
        t.whatId = null;
        update t;
        //Verify count = 0
        opp = [SELECT ID, activity_count__c FROM Opportunity WHERE ID = :opp.id];
        System.assertEquals(0,opp.activity_count__c);

        didRun = false; //Reset
        //Add an event
        Event e = new Event(subject='Test Event', whatId = opp.id, startDateTime = System.Now(), endDateTime = System.now());
        insert e;

        //Verify count = 1
        opp = [SELECT ID, activity_count__c FROM Opportunity WHERE ID = :opp.id];
        System.assertEquals(1,opp.activity_count__c);

        //Relink the task to the opportunity
        didRun = false; //Reset
        t.whatId = opp.id;
        update t;

        //Verify count = 2
        opp = [SELECT ID, activity_count__c FROM Opportunity WHERE ID = :opp.id];
        System.assertEquals(2,opp.activity_count__c);

        //Disconnect the event from the opportunity
        didRun = false; //Reset
        e.whatId = null;
        update e;

        //Verify count is back down to 1
        opp = [SELECT ID, activity_count__c FROM Opportunity WHERE ID = :opp.id];
        System.assertEquals(1,opp.activity_count__c);

        //Delete the task
        didRun = false; //reset
        delete t;
        //Verify count is back down to 0
        opp = [SELECT ID, activity_count__c FROM Opportunity WHERE ID = :opp.id];
        System.assertEquals(0,opp.activity_count__c);

    }
Jeff MayJeff May

On a Task record, the Opportunity is identified by the "WhatId".  The Lead or Contact associated with a Task is stored in the "WhoId".  So you'll want to check WhoId instead of WhatId, and make sure the ID starts with the "Lead prefix" of '00Q'

StevekBlueSnapStevekBlueSnap

everytime I enter 00Q it tells me expecting something else - right parenthesis or semi-colon not Q. Following my methodology from before and adding WhoID for What ID get me this error at line 5 of the trigger: Compile Error: Variable does not exist: LeadActivityCount.leadPrefix

Jeff MayJeff May

Make sure you update your controller class (in the example you posted, there is an oppPrefix variable.  That's the one you'll want to change to leadPrefix, and then change how its set accordingly.

StevekBlueSnapStevekBlueSnap

applied all similar changes to class (lead for opp and whoId for what ID and following error:

 

Compile Error: expecting right curly bracket, found 'EOF' at line 0 column -1

 

How do I get to line 0 if I'm starting at line 1?

Jeff MayJeff May

That means you have mis-matched open/closed curly braces.   If you're using Force IDE, you can put the mouse to the right of a curly brace, and a small square will highlight its partner.  You can use this to make sure all your code blocks are properly closed.

StevekBlueSnapStevekBlueSnap

yes - was missing end bracket line 96. Now I have new error:

 

Compile Error: Variable does not exist: leads at line 18 column 27

 

is that where prefix goes?