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
Ummang JainUmmang Jain 

Please help me in trigger code

Hey, so there is the scenario we are treating custom object contacts as student object we have field in that subject__c which is picklist, totalmarks__c and avgmarks__c(Average marks) then further we need to create marks as related list to contact which will have field subject_name__c and marksobtain__c so for that i created marks object as lookup to contact so now what will be trigger to update the field totalmarks__c and avgmarks__c in contact 
Anupama SamantroyAnupama Samantroy
Hi Ummang,

You can change the relationship from marks to student as Master Detail in that way you can create rollup fields for Average and Total Marks using configuration.
No need to trigger in that case.
Please let me know if you need more help on this.

Thanks
Anupama
Ummang JainUmmang Jain
Hey Anupama, ya that could be done but the requirement is to do by trigger so then how should i do that .
Anupama SamantroyAnupama Samantroy
Hi Ummang,

Please try below code.
trigger marksTrigger on Marks__c (after insert) {
	map<id,List<Marks__c>> mapMarksForStudent = new map<id,List<Marks__c>>();
	map<id,Contact> student = new map<Id, contact>();
	List<contact> toUpdate = new List<Contact>();
	for(Marks__c mark : trigger.new){
		if(!mapMarksForStudent.containsKey()){
			mapMarksForStudent.put(mark.Contact, new List<Marks__c>();
		}
		mapMarksForStudent.get(mark.contact).add(mark);
	}
	student = [Select id, totalmarks__c, avgmarks__c from Contact where ID in: mapMarksForStudent.keyset() ];
	for(Id studentId: mapMarksForStudent.keySet){
		Contact student =  mapMarksForStudent.get(studentId);
		for(marks__c mark: mapMarksForStudent.get(studentId)){
			student.totalmarks__c = student.totalmarks__c + mark.marksobtain__c;
		}
		student.avgmarks__c = student.totalmarks__c/(mapMarksForStudent.get(studentId).size());
		toUpdate.add(student);
	}
	update toUpdate;
}

Thanks
Anupama