To follow best practices, I am writing Apex Class instead of Apex Trigger. I have a Object called Drawing__c and Drawing_Line_Items__c having Lookup relationship. I want to update count of Drawing_Line_Items__c on Drawing__c. As per my Code Count is updating, but when I delete Drawing_Line_Items__c record, Count did not updating. Below is the code of Updating Count.Kindly anyone help with how to write class for Delete method and update count.
Apex Class:
public class DrawingLineitemsSendCountonDrawing {
public static void AfterInsert(List<Drawing_Line_Items__c> newList){
List<Drawing_Line_Items__c> DrawingList = new List<Drawing_Line_Items__c>();
List<Drawing__c> DrawList = new List<Drawing__c>();
Map<Id, List<Drawing_Line_Items__c>> DrawingLineItemsList = new Map<Id, List<Drawing_Line_Items__c>>();
Set<Id> DrawingIds = new Set<Id>();
//Map<String,String> DrawingLineItemsMap = New Map<String,String>();
for(Drawing_Line_Items__c draw :newList){
if(String.isNotBlank(draw.Drawing_Number__c) ){
DrawingIds.add(draw.Drawing_Number__c);
}
}
if(DrawingIds.size() > 0){
DrawingList = [SELECT Id, Shop_Drawing_Quantity__c, Drawing_Number__c FROM Drawing_Line_Items__c WHERE Shop_Drawing_Quantity__c != 0 AND Shop_Drawing_Quantity__c != NULL AND Drawing_Number__c IN : DrawingIds ];
for(Drawing_Line_Items__c draw : DrawingList) {
if(!DrawingLineItemsList.containsKey(draw.Drawing_Number__c)){
DrawingLineItemsList.put(draw.Drawing_Number__c, new List<Drawing_Line_Items__c>());
}
DrawingLineItemsList.get(draw.Drawing_Number__c).add(draw);
}
System.debug('Drawing Id and Drawing Line Items List Map is ' + DrawingLineItemsList);
DrawList = [SELECT Drawing_Line_Items_Count__c FROM Drawing__c WHERE Id IN : DrawingIds];
for(Drawing__c Drawing : DrawList) {
List<Drawing_Line_Items__c> DrawingList1 = new List<Drawing_Line_Items__c>();
DrawingList1 = DrawingLineItemsList.get(Drawing.Id);
Drawing.Drawing_Line_Items_Count__c= DrawingList1.size();
}
System.debug('Drawing List is ' + DrawList);
update DrawList;
}
}
}
Trigger Class:
trigger DrawingLineItems on Drawing_Line_Items__c (after insert, after Update, after delete, after undelete) {
// After Insert Count of Drawing Line Item goes to Drawing.
// Calling Class from Trigger
if(Trigger.isAfter){
DrawingLineitemsSendCountonDrawing.AfterInsert(Trigger.New);
}
}