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
Semira@gmail.comSemira@gmail.com 

Find previous child record and tag it

Hi, 

I'm wrecking my brain on how to achieve this. So I'm trying to run a child object from an apportunity. Child object may have multiple records. If so I need to find the previous entered record by comparing the recently created date with previous one. 

I'm writing an after insert trigger to achieve this. However, how do I find the previous records? I'm also trying to avoid nested for loops. So far this is what I have and giving me error: BudgetTrigger: execution of AfterInsert caused by: System.FinalException: Record is read-only Class.BudgetPreviousVersion.VersionUpdate: line 27
 
public without sharing class BudgetPreviousVersion {

    public static TriggerStatus__c cfg = TriggerConfig.raw;

    public static void VersionUpdate(list<Budget__c> budget){
        
        Set<Id> opportunityIds = new Set<Id>(); 
                
        for(Budget__c b: budget){
        
            if(b.Job__c != null){ 
                opportunityIds.add(b.Job__c);
                
            }
        }
        
        Map<ID, Budget__c> budmap = new Map<ID, Budget__c>();
        
        for(Budget__c b:[Select id, previous_version__c, CreatedDate From Budget__c WHERE job__c IN: opportunityIds order by createddate DESC limit 1]){
            
            budmap.put(b.id, b);                                 
        }
        
  List<budget__c> listb = new list<budget__c>();
       for(Budget__c b: budget){
           if(budmap.containskey(b.id)){
                 b.previous_version__c = true;                  

           }
           listb.add(b);
        }//for loop for each customer survey and assign them to customer survey.  */
         upsert listb;
    } 
}

Notice that I tried to upsert because upon searching it says the value is not yet commited. So upserting should update the value, right? How can I re-write this so I can avoid the nested loop? 
 
Dagny FernandesDagny Fernandes
Semira

Hi Semira,

As you are doing the after insert trigger here your query is giveing you the current record which you are inserting and you are updateing the same record so you are getting the error as "Record is read-only".

Change your Query to Below and Try: (Put some Dedug Statment and Check which the record you are processing)
//Get budget Id
List<Id> budgetId = new List<Id>();
for(budget__c b: Trigger.New){
   budgetId.add(b.Id);
}
//Change the Query
Select id, previous_version__c, CreatedDate From Budget__c WHERE job__c IN: opportunityIds AND Id NOT IN budgetId order by createddate DESC limit 1