+ Start a Discussion
Team WorksTeam Works 

Any improvements/suggestions for this trigger?

Hello All,

New coder in Apex here
Just need suggestions from the experienced people out there if my trigger is efficient and scalable? Many Thanks for you help in advance. Also if someone can suggest how to proceed for a test class for this trigger..i apppreciate your help

// This trigger counts all of the calls made for a particular record type and Event Type  in Event //Displays the count on Account Pagetrigger Activity_Count on Event (after insert, after update, after delete) {      Set<Id> eventIds = new Set<Id>();     Set<Id> accIds = new Set<Id>();     Map<Id,Account> accMap = new Map<Id,Account>();     List<Account> updateList = new List<Account>();      String accPrefix = Account.sObjectType.getDescribe().getKeyPrefix();     system.debug(accPrefix);     for (Event e : Trigger.isDelete ? Trigger.old : Trigger.new)         {            eventIds.add(e.Id);            String str = e.whatId;            if(str != null && str.startsWith(accPrefix)) // Task belongs to Account                    accIds.add(e.whatId);            }      integer countercalls = 0;      integer countermeetings = 0;      //system.debug('This is the list of the account Ids selected related to Task ----'+accIds);      if(accIds.size() > 0)          {          for(Account acc : [SELECT Id, Annual_Actuals_Calls__c,Annual_Actuals_Meetings__c FROM Account WHERE Id in :accIds]){             for(Event evt :[SELECT Id, RecordTypeId,Type FROM Event where WhatId = :acc.Id]){               If(evt.RecordTypeId == '01220000000YZcPAAW' && evt.Type == 'Sales Call')                 countercalls +=1;               If(evt.RecordTypeId == '01220000000YZcPAAW' && (evt.Type == 'Sales Visit' || evt.Type == 'New Client Visit'))                 countermeetings +=1;               }             acc.Annual_Actuals_Calls__c = countercalls;             acc.Annual_Actuals_Meetings__c = countermeetings;             updateList.add(acc);           }                 }       if(updateList.size() > 0)         {           //system.debug('The list to be updated contains these accounts :-----'+updateList);           upsert updateList;         }  }
sfdc integrator.ax1790sfdc integrator.ax1790
Try This in your test class

Account acc=new Account();
insert acc;

Event evnt1=new Event();
evnt1.name='New Event Test';
evnt1.Type='sales Call';
evnt1.RecordTypeId == '01220000000YZcPAAW'
insert evnt1;

Event evnt2=new Event();
evnt2.name='New Event Test';
evnt2.Type='Sales Visit';
evnt2.RecordTypeId == '01220000000YZcPAAW'

insert evnt2;
I would suggest not to hardcode the recordtype Ids as it is not as per the best practices of salesforce.

Try to query the RecordtypeId and then use it in your test class something like below :-

select id from RecordType where DeveloperName ='<some name>' and SobjectType='Account'