+ 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>();
        for(Student__c s: Trigger.New){
	}else if (Trigger.IsDelete){
		for(Student__c s: Trigger.Old){
        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')));
            update courseList;