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
yp reddyyp reddy 

trigger code for count operation

Hi, i want to write trigger code for the following requirement. i have two objects courses and students .
in course object i have two fields coursename and no of students. in student object i have Name and a lookup field (with course object). if a student  select a course the no of student field count should be incresed.if i delete a student  the count should be decresed.
Salesforce DeveloperSalesforce Developer
Try as below:
trigger RollUpSummary on Student__c (after insert, after delete) {
    Set<Id> courseId = new Set<Id>();
    if(Trigger.IsInsert){
        for(Student__c s: Trigger.New){
            courseId.add(s.course__c);
        }
	}else if (Trigger.IsDelete){
		for(Student__c s: Trigger.Old){
            courseId.add(s.course__c);
        }    
	}
    if(!courseId.isEmpty()){
        List<Student__c> Newstudent = new list<Student__c>();
        List<course__c> courseList = new list<course__c>();
        
        for(AggregateResult s:[SELECT Course__r.Id cid, Count(Id) counte FROM Student__c WHERE course__r.Id IN : courseId GROUP BY Course__r.Id]){
            
            courseList.add(New course__c(Id=(Id)s.get('cid'), No_of_Students__c = (Integer)s.get('counte')));
        }
        
        if(!courseList.IsEmpty())
            update courseList;
    }

}