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
Certification PracticeCertification Practice 

What I want is to update the Parent_Record__c(self lookup field) field if the no. of records with the same name is 10.If I have 30 record then 2-10 have parent as record 1...12-20 record have parent as record 11...and 22-30 record have parent 21..

public class AddParentonCreateHandler {
    public static void addParentMethod(List<Student__c> stulist){
        
       
        String ParentIds ;
        Set<Id> ChildIds = New Set<Id>();
        List<Student__c> listtoupdate  = New List<Student__c>();
        List<Student__c> FinalList  = New List<Student__c>();
        List<Student__c> oldrecord = [SELECT Id,Name,Parent_Record__c,Roll_No__c FROM Student__c WHERE Parent_Record__c = null ORDER BY Roll_No__c DESC ];
        
        if(!oldrecord.isEmpty() && oldrecord.size()> 9){
            for(Student__c stu : stulist ){
                for(Student__c ostu : oldrecord){ 
                    if(stu.Name == ostu.Name ){
                        if(ChildIds.size() < 9){
                            ChildIds.add(ostu.id);  
                            
                        } 
                        else{
                            if(ParentIds ==  null){
                                ParentIds =   ostu.id;
                              
                            }
                            if(ChildIds.size() < 11  && ParentIds != null ){
                                for(Student__c stu2 : [SELECT Id,Parent_Record__c,Roll_No__c FROM Student__c WHERE ID IN : ChildIds  AND ID !=: ParentIds ORDER BY Roll_No__c DESC]){
                                    stu2.Parent_Record__c = ParentIds;
                                    listtoupdate.add(stu2);
                                }
                                
                                ChildIds.clear(); 
                                ParentIds = null;
                           }
                        }    
                    }
                } 
            }
            UPDATE listtoupdate;
        }
        
    }
}

 
Certification PracticeCertification Practice
Further to it if I have 5 more records lets say 31-35 then it does not get updated because I want to update Parent_Record__c field only if the no. of record without Parent_Record__c is 10. this code does not work fine...