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
Agnibha Chakrabarti 10Agnibha Chakrabarti 10 

trigger in junction object relationship to update field value

hi,
my requirement is

 After the batch is over, Teacher will mark the batch as complete. Then the course will be moved from Requested Courses to Completed Coursed for all the students of the batch. Before marking a batch as complete, the teacher can remove any student from the batch. This will not be possible after the batch is completed.
this is the relationshipi have to transfer the value(TEXT) from requested course to completed course of Student object when the ceck box of completed couse on Batch object is checked.
i wrote the trigger:
trigger Batch on Batch__c (after update) {

    List<String> b= new List<String>();  

     for(Batch__c p: Trigger.new){
         if(p.complted__c==true){
         b.add(p.Name);

     }     }

    List<Student_Batch_Junction__c > c=new List<Student_Batch_Junction__c>([select Student__r.Name from Student_Batch_Junction__c where Batch__r.Name in :b]);   
    system.debug(c);
    List<Student__c> s=new List<Student__c>([select Student__c.Name from Student__c]);
    integer i=0;
    for(Student__c o : s)
    {     if(o.Name.equals(c))
    {
        
        	o.Completed_Courses__c=o.Requested_Courses__c;
          Update o;
    }
   
        
    }
    
}

but its not working
Deepali KulshresthaDeepali Kulshrestha
Hi Agnibha,

There are some few changes you should do on your code,and i've updated your code you can check below:

(Note: it works if your relationship is master detail,and if it is not just change it.Hope it will work)
 
trigger Batch on Batch__c (after update) {

List<String> b= new List<String>(); 

 for(Batch__c p: Trigger.new){

     if(p.complted__c==true){
     b.add(p.Name);

 }     }

List<Student_Batch_Junction__c > c=new List<Student_Batch_Junction__c>([select Student.Id,Student__r.Name from Student_Batch_Junction__c where Batch__r.Name in :b]); 
Set<Id> allstudentBatchId=new Set<Id>();
for(Student_Batch_Junction__c stdjunction :c)
{
 allstudentBatchId.add(stdjunction.Student.Id);
}


List<Student__c> s=new List<Student__c>([select Student__c.Name from Student__c where Id IN: allstudentBatchId]);
List<Student__c> updateStudent=new List<Student__c>();
for(Student__c stud : s)
{     if((stud.Name).equals(c))
      {
      stud.Completed_Courses__c=stud.Requested_Courses__c;
      updateStudent.add(stud);
      }

}
if(updateStudent.size()>0)
update updateStudent;


}
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com