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
LisaSturzLisaSturz 

Code to count completed activities on a contact

I would like to tweak the apex code in the link below to count the number of activities on the CONTACT object and only if the activity status = "COMPLETED". Does anyone know how I can do that?

 

Link: http://www.radialweb.com/2010/08/summarizing_salesforce_fields_with_triggers/#comments

LisaSturzLisaSturz

This is what I have so far...everything is working besides status=Completed:

 

public with sharing class ContactActivityCount {

    public static Boolean didRun = false;
    public static String conPrefix =  Contact.sObjectType.getDescribe().getKeyPrefix();

    /*
    * Takes a set of contact IDs, queries those contacts, and updates the activity count if appropriate
    */
    public static void updateContactCounts(Set<ID> conIds) {

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

            //Query all the contacts, including the tasks child relationships
            List<Contact> con = [SELECT ID, activity_count__c, (SELECT ID FROM Tasks), (SELECT ID FROM Events) FROM Contact WHERE ID IN :conIds];
            List<Contact> updateCons = new List<Contact>();

            for (Contact o : con) {
                Integer count = o.tasks.size() + o.events.size();

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

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

   }