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
HARSHIL U PARIKHHARSHIL U PARIKH 

Trigger don't delete the last record.

Hello Developers!
I was wondering if I can use your help on following trigger.
Trigger works FINE for all conditions accept when the last record is deleted.
About Trigger:
Two Object with Parent-Child lookup relationship.
Object-1 = Contact as Parent
Object-2 = Merchandise__C as Child.

Count "Transaction_Count__C" on Contact means just counting number of Merchandise__c records for Contact.
Count "Total_Money_Spent_for_ACA_Products__c " on Contact means count sum of all Transaction_Total__c from Merchandise__c.

How Merchandise__C look up to contact? - By Individual_Customer__c field.

Trigger:
Trigger TotalTransCostCount on Merchandise__C( after insert, after update,after delete,after undelete) {
     Set<Id> ConIdSet = new Set<Id>();
     List<Contact> ConListToUpdate = new List<Contact>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Merchandise__C Merch: Trigger.new)
        {
            if(Merch.Individual_Customer__C != null)
                {
                    ConIdSet.add(Merch.Individual_Customer__C);
                }     
        }
    }
    If(Trigger.isDelete)
    {
       for(Merchandise__C Merch: Trigger.old)
       {
            if(Merch.Individual_Customer__C != null)
            {
                ConIdSet.add(Merch.Individual_Customer__C );    
            } 
        }
    }
   for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C ,sum(Transaction_Total__c)addition FROM Merchandise__C WHERE 
                                                                       Individual_Customer__C IN :ConIdSet group by Individual_Customer__C ]) 
        {
                ConListToUpdate.add(new Contact         (     Id=(Id)res.get('Individual_Customer__C'), 
                                                              Total_Money_Spent_for_ACA_Products__c =  (Double)res.get('addition'),
                                                              Transaction_Count__C =  (Integer)res.get('Quantity')     )     
                                   );
        }
    try
    {
      update ConListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}
Problem:
If I create 3 merchandise__c records with all have Transaction_Total__c = 10 for contact named John Doe then Total_Money_Spent_for_ACA_Products__c becomes 30 for him.
Now if I delete one record then it becomes 20.
Then delete another record it comes 10.
Now, If I delete his last record then it still stays to 10.??
Thank You!
 
Best Answer chosen by HARSHIL U PARIKH
Alain CabonAlain Cabon

1) if(Trigger.IsDelete & MapConToReset.containsKey(  (Id)res.get('Individual_Customer__C') 

2) for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C ,sum(Transaction_Total__c)addition FROM Merchandise__C WHERE                                                                     Individual_Customer__C IN :ConIdSet group by Individual_Customer__C ])

Alain

All Answers

Alain CabonAlain Cabon
Hello Govind Guru,

After deleting the last merchandise__c, 

for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C ,sum(Transaction_Total__c)addition FROM Merchandise__C WHERE Individual_Customer__C IN :ConIdSet group by Individual_Customer__C ])

... will get no res values for some  Individual_Customer__C  at all and you will not update these contacts.

For all the Individual_Customer__C , you need a first map of contact to update with the reset values :

MapConToReset.put( <each 'Individual_Customer__C'>, new Contact ( Id= <each 'Individual_Customer__C'>, Total_Money_Spent_for_ACA_Products__c = 0, ...);

In the for loop  ( for(AggregateResult res), you remove the pre-existing Individual_Customer__C contact in the MapConToReset.

After the for loop, you add the remaining contacts to reset in MapConToReset into ConListToUpdate.

Alain
HARSHIL U PARIKHHARSHIL U PARIKH
Thank you for followup!
Do you mean something like this,
Error: Error: Compile Error: expecting a right parentheses, found '<' at line 27 column 23
Trigger TotalTransCostCount on Merchandise__C( after insert, after update,after delete,after undelete) {
     Set<Id> ConIdSet = new Set<Id>();
     List<Contact> ConListToUpdate = new List<Contact>();
    
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Merchandise__C Merch: Trigger.new)
        {
            if(Merch.Individual_Customer__C != null)
                {
                    ConIdSet.add(Merch.Individual_Customer__C);
                }     
        }
    }
    If(Trigger.isDelete)
    {
       for(Merchandise__C Merch: Trigger.old)
       {
            if(Merch.Individual_Customer__C != null)
            {
                ConIdSet.add(Merch.Individual_Customer__C );   
            } 
        }
    }
    
    MapConToReset.put( <each 'Individual_Customer__C'>, new Contact 
                                                                   ( Id= <each 'Individual_Customer__C'>, 
                                                                   Total_Money_Spent_for_ACA_Products__c = 0, 
                                                                   Transaction_Count__C  = 0 ));
    
   for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C , sum(Transaction_Total__c)addition FROM Merchandise__C WHERE 
                                                                       Individual_Customer__C IN :MapConToReset group by Individual_Customer__C ]) 
        {
                ConListToUpdate.add(new Contact         (     Id=(Id)res.get('Individual_Customer__C'), 
                                                              Total_Money_Spent_for_ACA_Products__c =  (Double)res.get('addition'),
                                                              Transaction_Count__C =  (Integer)res.get('Quantity')     )     
                                   );
                                   
            
        }
        ConListToUpdate.add(MapConToReset);
    try
    {
      update ConListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}


 
Alain CabonAlain Cabon

1) Each Individual_Customer__C of the Trigger.old

Map<Id,Contact>  MapConToReset  = new Map<Id,Contact>();

If(Trigger.isDelete) { for(Merchandise__C Merch: Trigger.old) { if(Merch.Individual_Customer__C != null) {         ConIdSet.add(Merch.Individual_Customer__C );

MapConToReset.put( Merch.Individual_Customer__C, new Contact ( Id= Merch.Individual_Customer__C,
Total_Money_Spent_for_ACA_Products__c = 0, Transaction_Count__C = 0 ));

} } }

2) for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C ,   : don't change IN:MapConToReset

is like before but contains just :

MapConToReset.remove((Id)res.get('Individual_Customer__C'));

Alain
Alain CabonAlain Cabon
3)   ConListToUpdate.add(MapConToReset); is not possible

for ( ID cid : MapConToReset.keySet() ){
      ConListToUpdate.add((Contact)MapConToReset.get(cid));
}

Alain
HARSHIL U PARIKHHARSHIL U PARIKH
Thank you & Getting really closer but Error: Compile Error: expecting an equals sign, found '(' at line 35 column 82
Trigger TotalTransCostCount on Merchandise__C( after insert, after update,after delete,after undelete) {
     Set<Id> ConIdSet = new Set<Id>();
     List<Contact> ConListToUpdate = new List<Contact>();
     Map<Id,Contact>  MapConToReset  = new Map<Id,Contact>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Merchandise__C Merch: Trigger.new)
        {
            if(Merch.Individual_Customer__C != null)
                {
                    ConIdSet.add(Merch.Individual_Customer__C);
                }     
        }
    }
   If(Trigger.isDelete) 
      { 
       for(Merchandise__C Merch: Trigger.old) 
           { 
               if(Merch.Individual_Customer__C != null) 
                   {     
                           ConIdSet.add(Merch.Individual_Customer__C );
                           MapConToReset.put( Merch.Individual_Customer__C, new Contact ( Id= Merch.Individual_Customer__C,
                                                                                           Total_Money_Spent_for_ACA_Products__c = 0, Transaction_Count__C = 0 ) );
                   } 
           } 
       }
    
   for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C , sum(Transaction_Total__c)addition FROM Merchandise__C WHERE 
                                                                       Individual_Customer__C IN :ConListToUpdate group by Individual_Customer__C ]) 
        {
                ConListToUpdate.add(new Contact         (     Id=(Id)res.get('Individual_Customer__C'), 
                                                              Total_Money_Spent_for_ACA_Products__c =  (Double)res.get('addition'),
                                                              Transaction_Count__C  = (Integer)res.get('Quantity'),   
                                                              MapConToReset.remove(  (Id)res.get('Individual_Customer__C')  )   
                                                        );
                                   
            
        }
        for ( ID cid : MapConToReset.keySet() )
        {
          ConListToUpdate.add((Contact)MapConToReset.get(cid));
        }
    try
    {
      update ConListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}


 
Alain CabonAlain Cabon
Move       MapConToReset.remove(  (Id)res.get('Individual_Customer__C')  )    after );  and add a semi-column (it is a new line of code)
Alain
HARSHIL U PARIKHHARSHIL U PARIKH
Tanks again for followup and now trigger saves:) But Transaction_Count__C and Total_Money_Spent_for_ACA_Products__c remains zero all the time whether I create a child record ot delete a child record.
Trigger TotalTransCostCount on Merchandise__C( after insert, after update,after delete,after undelete) {
     Set<Id> ConIdSet = new Set<Id>();
     List<Contact> ConListToUpdate = new List<Contact>();
     Map<Id,Contact>  MapConToReset  = new Map<Id,Contact>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Merchandise__C Merch: Trigger.new)
        {
            if(Merch.Individual_Customer__C != null)
                {
                    ConIdSet.add(Merch.Individual_Customer__C);
                }     
        }
    }
   If(Trigger.isDelete) 
      { 
       for(Merchandise__C Merch: Trigger.old) 
           { 
               if(Merch.Individual_Customer__C != null) 
                   {     
                           ConIdSet.add(Merch.Individual_Customer__C );
                           MapConToReset.put( Merch.Individual_Customer__C, new Contact ( Id= Merch.Individual_Customer__C,
                                                                                           Total_Money_Spent_for_ACA_Products__c = 0, Transaction_Count__C = 0 ) );
                   } 
           } 
       }
    
   for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C , sum(Transaction_Total__c)addition FROM Merchandise__C WHERE 
                                                                       Individual_Customer__C IN :ConListToUpdate group by Individual_Customer__C ]) 
        {
                ConListToUpdate.add(new Contact         (     Id=(Id)res.get('Individual_Customer__C'), 
                                                              Total_Money_Spent_for_ACA_Products__c =  (Double)res.get('addition'),
                                                              Transaction_Count__C  = (Integer)res.get('Quantity') 
                                                                
                                                        ) );
                                                        
            MapConToReset.remove(  (Id)res.get('Individual_Customer__C')  );
                                   
            
        }
        for ( ID cid : MapConToReset.keySet() )
        {
          ConListToUpdate.add((Contact)MapConToReset.get(cid));
        }
    try
    {
      update ConListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}

Thanks you for all suggestions!
 
Alain CabonAlain Cabon
Enclose  MapConToReset.remove(  (Id)res.get('Individual_Customer__C')  );  with  If(Trigger.isDelete) {  ... }
HARSHIL U PARIKHHARSHIL U PARIKH
Yup... Did that as well but same thing. Those two fields still staying as zero....
Trigger TotalTransCostCount on Merchandise__C( after insert, after update,after delete,after undelete) {
     Set<Id> ConIdSet = new Set<Id>();
     List<Contact> ConListToUpdate = new List<Contact>();
     Map<Id,Contact>  MapConToReset  = new Map<Id,Contact>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Merchandise__C Merch: Trigger.new)
        {
            if(Merch.Individual_Customer__C != null)
                {
                    ConIdSet.add(Merch.Individual_Customer__C);
                }     
        }
    }
   If(Trigger.isDelete) 
      { 
       for(Merchandise__C Merch: Trigger.old) 
           { 
               if(Merch.Individual_Customer__C != null) 
                   {     
                           ConIdSet.add(Merch.Individual_Customer__C );
                           MapConToReset.put( Merch.Individual_Customer__C, new Contact ( Id= Merch.Individual_Customer__C,
                                                                                           Total_Money_Spent_for_ACA_Products__c = 0, Transaction_Count__C = 0 ) );
                   } 
           } 
       }
    
   for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C , sum(Transaction_Total__c)addition FROM Merchandise__C WHERE 
                                                                       Individual_Customer__C IN :ConListToUpdate group by Individual_Customer__C ]) 
        {
                ConListToUpdate.add(new Contact         (     Id=(Id)res.get('Individual_Customer__C'), 
                                                              Total_Money_Spent_for_ACA_Products__c =  (Double)res.get('addition'),
                                                              Transaction_Count__C  = (Integer)res.get('Quantity') 
                                                                
                                                        ) );
                                                        
            if(Trigger.IsDelete)
            {
                MapConToReset.remove(  (Id)res.get('Individual_Customer__C')  );
            }
           
        }
        for ( ID cid : MapConToReset.keySet() )
        {
          ConListToUpdate.add((Contact)MapConToReset.get(cid));
        }
    try
    {
      update ConListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}

 
Alain CabonAlain Cabon

1) if(Trigger.IsDelete & MapConToReset.containsKey(  (Id)res.get('Individual_Customer__C') 

2) for(AggregateResult res : [SELECT Count(id)Quantity, Individual_Customer__C ,sum(Transaction_Total__c)addition FROM Merchandise__C WHERE                                                                     Individual_Customer__C IN :ConIdSet group by Individual_Customer__C ])

Alain
This was selected as the best answer
HARSHIL U PARIKHHARSHIL U PARIKH
Thank You!! All Set!!!!!