0

Here is the scenario! I've student object(Parent object) with fields-:

Name

T_Amount__c

and course object(child) with fields-:

Name,

FeeAmount__c,

Student__c(lookup field)

I've written a trigger where on adding values on FeeAmount__c in child, the parent object field T_Amount__c should be updated with sum(FeeAmount__c).

Problem: My trigger is working for both insert and update but it is not letting me delete any records in course object.

Here is my code for the same please have a look.

Trigger SumTotalFees on Course__c  (after insert, after update, after delete) {
    
    Set<Id> studentIds = new Set<Id>();
    List<Student__c> StudentsToUpdate = new List<Student__c>();

    for (Course__c c : Trigger.new) {
        studentIds.add(c.Student__c);
    }

    if (Trigger.isUpdate || Trigger.isDelete) {
        for (Course__c c : Trigger.old) {
            StudentIds.add(c.Student__c);
        }
    }

    Map<id, Student__c> studentMap = new Map<id, Student__c>([select id, T_Amount__c  from Student__c where id IN :studentIds]);

    List<AggregateResult> ars = [SELECT Student__c, sum(FeeAmount__c) FROM Course__c WHERE Student__c  IN :studentIds group by Student__c ];
    
    for (AggregateResult ar : ars) {
        studentMap.get(String.valueOf(ar.get('Student__c'))).T_Amount__c  = Integer.valueOf(ar.get('expr0'));
        StudentsToUpdate.add(studentMap.get(String.valueOf(ar.get('Student__c'))));
    }
    update StudentsToUpdate;
}
0
1

After delete does not have Trigger.new, so you should add if-clause to the first for-loop like:

if (Trigger.isUpdate || Trigger.isInsert) {
    for (Course__c c : Trigger.new) {
        studentIds.add(c.Student__c);
    }
}
1
  • Thanks, it worked. Just learnt new thing from you :) I Appreciate your help Jun 24 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.