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
Mayank07Mayank07 

my trigger is not updating parent object record

Hi, i am creating three child records when a record is created on parent object using process builder. now,  i am writing a trigger to update 'status__c = closed' field on parent object when status of three child record's is marked as 'completed'. 
below is my apex method
public class StatusClosedHandler { 
     public static void statuschange(List<Id> RecordId){ 
         integer count = 0; 
         List<Service_Request__c> srequest = new List<Service_Request__c>();
         for(Service_Line__c sl : [Select id, Name, Status__c,Line_Type__c, Service_Request__r.Status__c,Service_Request__r.Name from Service_Line__c WHERE Id IN :RecordId]){
         if(sl.Status__c == 'Completed'){ 
         count++;
 } 
         if(count == 3){
         Service_Request__c sr = new Service_Request__c();
         sr.id = sl.Service_Request__c;
         sr.status__c = 'Closed';
         srequest.add(sr);
 } 
 }
          update srequest;
 } 
}

and my trigger to call this method is :
trigger StatusClosedfinal on Service_Line__c (after update) {
    if(Trigger.isAfter && Trigger.isUpdate){ 
   List<Id> sLine = new List<Id>();
    for(Service_Line__c  i:trigger.new) {
        sLine.add(i.Id);
}
     StatusClosedHandler.statuschange(sLine); 
} 
}

when i am running method in anonymous window and passing parent id as a list, it's updating the status, but not while runnig the trigger.
​​​​​​​please help
{tushar-sharma}{tushar-sharma}
I see many errors in your code.
1. What if the count is greater then 3 then your code won't work.
2. You are not considering parent and child. You should query child in inner query and if the count is 3+ then update the status.
3. If they are in Master-Detail I suggest you use rollup to calculate number and update field.

sample code
Send Parent Id in method
//Just adding psudo code, check API names
public static void statuschange(List<Id> RecordId){ 
         
         List<Service_Request__c> srequest = new List<Service_Request__c>();
         for(Service_Line__c sl : [Select id, (SELECT ID, Status__c FROM Service_Request__r) from Service_Line__c WHERE Id IN :RecordId]){
         integer count = 0; 
        for(Service_Line__c: sl.Service_Request__r) {
         if(sl.Status__c == 'Completed')
             count++;
 
         if(count >= 3){
         sl.status__c = 'Closed';
         srequest.add(sr);
          } 
        }
     }
          update srequest;
 }

If this answer helps you, please mark it as accepted.

Regards,
Tushar Sharma
https://newstechnologystuff.com/