• Vrajesh Sheth
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

Hello,

 

I was wondering if someone would be able to help me bulifying the trigger below.  As of now, this trigger counts all of the calls made in one month on a particular account made by a particular system profile.

 

I just was given the requirements that I need to do the same thing but for another profile, AL - AM Rep and write to a different field, AM_Activity_Count__c.  I know I could just duplicate this trigger, change the name in the soql, and then save it.  But I know there has to be a way that I can bulkify this.  I've been messing around trying to get this to work and I've been unable to get it to work so far.  Here't what I have originally:

 

 

trigger Activity_Count on Task (after insert, after update, after delete) 
{
    List<Id> taskIds = new List<Id>();
    List<Id> accIds = new List<Id>();
    Map<Id,Account> accMap = new Map<Id,Account>();
    List<Account> updateList = new List<Account>();  // edited
    String accPrefix = Account.sObjectType.getDescribe().getKeyPrefix();
    
    for (Task t : Trigger.isDelete ? Trigger.old : Trigger.new)
    {
        taskIds.add(t.Id);
        String str = t.whatId;
        if(str != null && str.startsWith(accPrefix))     // Task belongs to Account
          {
            accIds.add(t.whatId);
          }
    }
    
    if(accIds.size() > 0)
    {
        for(Account ac : [SELECT Id, Activity_Count__c FROM Account WHERE Id in :accIds])
        {
            accMap.put(ac.Id,ac);
        }

        for(AggregateResult ar : [SELECT Count(Id) c, WhatId w, Owner.Profile.Name
                                  FROM Task
                                  WHERE whatId IN :accIds
                                  AND Subject Like 'Call%'
                                  AND CreatedDate = This_Month
                                  AND Owner.Profile.Name = 'AL - AS Rep'
                                  GROUP BY WhatId, Owner.Profile.Name])
        {
            Account acc = new Account();
            
            string str = string.valueOf(ar.get('w'));
            
            acc = accMap.get(str);   // Edited   //
            acc.Activity_Count__c = Integer.valueOf(ar.get('c'));   // Edited
            
            updateList.add(acc);
        }
    }
    
    if(updateList.size() > 0)
    {
        update updateList;
    
    }
}