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
Brijesh Kumar 21Brijesh Kumar 21 

roll-up summary to calculate total amount on custom object having lookup relationship with other custom object

I have two Custome Object 1. Students with having field of 
1.StudentName
2.joining
3.Duration
4.TotalAmount
and another object is 2. My Courses with having field of
1.CourseName
2.FeeAmount
3.TeacherName
student object will be perent and other will child how we can calculate sum of FeeAmount to the total amount using triggerd rollup summery..
Ravi Dutt SharmaRavi Dutt Sharma
Can be done through trigger, but I would suggest you to avoid that route. The data model seems to be incorrect to me. Course should not be a child object of Student. Student and Course are independent objects. Student and Course should have many to many relationship. Create a junction object between Student and Course.
Steven NsubugaSteven Nsubuga
Assuming that name of lookup field is called Student__c, and that Student__c is the parent and Course__c is the child object.
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, TotalAmount__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 '))).total_hr__C  = Integer.valueOf(ar.get('expr0'));
        StudentsToUpdate.add(studentMap.get(String.valueOf(ar.get('Student__c '))));
    }

    update StudentsToUpdate;
}

 
v varaprasadv varaprasad
Hi ,

Please check once below code : 
 
trigger RollupSummaryTriggerOnAccountObj on contact(after insert, after update, after delete, after undelete) {
    if (trigger.isAfter && (trigger.isInsert || trigger.isUpdate || trigger.isUndelete)) {
        SampleRollupSummary.rollupContacts(trigger.new);
    }
    else if (trigger.isAfter && trigger.isDelete) {
        SampleRollupSummary.rollupContacts(trigger.old);
    }
}


its related class :

public class SampleRollupSummary {
  
    public static void rollupContacts(list<contact> lstOfconts){
        system.debug('==lstOfconts== : '+lstOfconts);
        set<id> accIds = new set<id>();
        list<account> updLstOfAccs = new list<account>();
        list<contact> lstCons = new list<contact>();
      
        for(contact con : lstOfconts){
    if(con.accountid != null)
            accIds.add(con.accountid);
        }
        system.debug('==accIds==:'+accIds);
        list<account> lstAccs = [select id,name,Totalamount__c, (select id,amount_c from contacts) from account where id in : accIds];
      
        for(account acc : lstAccs){
            system.debug('==acc.contacts.size()=='+acc.contacts.size());
			deimal sumamt = 0;
           if(acc.contacts.size() >0)
           for(contact co : acc.contacts){
		       if(co.amount_c != null)
               sumamt = sumamt+co.amount_c;            
            }
		acc.Totalamount__c = sumamt;
		updLstOfAccs.add(acc);
		}
        if(updLstOfAccs.size() > 0){
            update updLstOfAccs;
        }
      
      
    }
  
}

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com
Blog: http://salesforceprasad.blogspot.com/
Salesforce latest interview questions  :
https://www.youtube.com/channel/UCOcam_Hb4KjeBdYJlJWV_ZA?sub_confirmation=1


 
Brijesh Kumar 21Brijesh Kumar 21
Hello Sir, @Steven Nsubuga

I think I can relate this answer but I have confusion on fields that you mentioned in code which is look-up relation and where the code is making the relationship between two of them plz explain sir.
Brijesh Kumar 21Brijesh Kumar 21
sir triggger is no throwning any error but what is total hr and where i need to create this object and why the total fee is not showing in student object please correct me.
Steven NsubugaSteven Nsubuga
My mistake, total hr is supposed to be TotalAmount__C.
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, TotalAmount__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 '))).TotalAmount__C  = Integer.valueOf(ar.get('expr0'));
        StudentsToUpdate.add(studentMap.get(String.valueOf(ar.get('Student__c '))));
    }
    update StudentsToUpdate;
}

 
Brijesh Kumar 21Brijesh Kumar 21
Ok Do I need to create test class as well for the trigger to code coverage?
Brijesh Kumar 21Brijesh Kumar 21
bcaus it still not showing any total amount on student object.
Brijesh Kumar 21Brijesh Kumar 21
SumTotalFees: execution of AfterUpdate caused by: System.SObjectException: Invalid field Student__c for AggregateResult Trigger.SumTotalFees: line 29, column 1 
I am getting this error now.
Steven NsubugaSteven Nsubuga
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, TotalAmount__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'))).TotalAmount__C  = Integer.valueOf(ar.get('expr0'));
        StudentsToUpdate.add(studentMap.get(String.valueOf(ar.get('Student__c'))));
    }
    update StudentsToUpdate;
}

 
Brijesh Kumar 21Brijesh Kumar 21
@isTest
public class RollUpTest {

    static Student__c createStudent(String name, ID StudentId){
        
        Student__c s = new Student__c();
        s.Name = name;
        s.S_ID__c = StudentId;
        insert s;
        return s;
    }
    
    static testMethod void addCourses(){
        
        Set<Id> studentIds = new Set<Id>();
        integer studentIdsOne ;
        integer studentIdsTwo ;
        
        Student__c sid1 = new Student__c();
        sid1.Name = 'ZZ00034X';
        insert sid1;
        
        Student__c student1 = createStudent('Student 1',sid1.id);
        Student__c student2 = createStudent('Student 2',sid1.id);

        List<Course__c> CourseItems = new List<Course__c>();
        
        for (Integer i=0;i<studentIdsOne;i++) {

            Course__c CourseItem = new Course__c();
            CourseItem.Name = 'LP'+i;
            CourseItem.Student__c = student1.Id;

            CourseItems.add(CourseItem);

        }
        for (Integer i=0;i<studentIdsTwo;i++) {

            Course__c CourseItem = new Course__c();
            CourseItem.Name = 'LP10'+i;
            CourseItem.Student__c = student2.Id;

            CourseItems.add(CourseItem);

        }
        
        insert CourseItems;

        
        studentIds.add(student1.Id);
        studentIds.add(student2.Id);
        
        Map<id,Student__c> StudentMap = new Map<id,Student__c>([select Id, Name, Total_Amount__c from Student__c where Id IN :StudentIds]);

        System.assertEquals(studentIdsOne,StudentMap.get(student1.Id).Total_Amount__c);
        System.assertEquals(studentIdsTwo,StudentMap.get(student2.Id).Total_Amount__c);
        
        CourseItems.get(0).Student__c = null;
        update CourseItems.get(0);
        
        Student__c student3 = [select Total_Amount__c from Student__c where Id = :student1.id];
        
        System.assertEquals(studentIdsOne-1,Student3.Total_Amount__c);

    }
   
}



my test class is giving assertion failed error and out of bound 0 error can you help me out with the test class sir.
Steven NsubugaSteven Nsubuga
@isTest
public class RollupTest {

    @isTest static void testTrigger() {
		List<Student__c> students = new List<Student__c>;
		for (Integer i = 1; i < 3; i++){
			Student__c student = new Student__c(Name = 'student'+i, S_ID__c = 'Id'+i, TotalAmount__c = 0);
			students.add (student);
		}
		insert students;
		 
		List<Course__c> courses = new List<Course>();
		courses.add(new Course__c(Student__c = students[0].Id, FeeAmount__c = 250, Name = 'C0'));
		for (Integer j = 1; j < 5; j++){
			Course__c course = new Course__c(Student__c = students[1].Id, FeeAmount__c = 200 + j; Name = 'C'+j);
			courses.add(course);
		}
		insert courses;

		List<Student> students = [SELECT TotalAmount__c FROM Student__c order by Name ASC];

		System.assert(students[0].TotalAmount__c == 250);
		System.assert(students[1].TotalAmount__c == 810);
	}
}

 
Shubham Joge 9Shubham Joge 9
roll-up summary to calculate total amount of child on case parent object 
i am having one standard case object on which case are created .Case object is have one lookup filed ie [parent case]
now i have to write one trigger on case object  parent case should have the cout of no of child object .
can anyone please help me with this trigger?