+ Start a Discussion
Vamsi VaddipalliVamsi Vaddipalli 

Update existing child records when new child record get inserted for the same parent

Hi,
I have one scenario - Whenever new child get inserted existing child records get update for the same Parent.
Parent:STD__c
Child:Attended__c.
Trigger:
trigger IsLatestAtt on Attended__c (after insert) {
    IsLatestAttClass.met(Trigger.new);
}
Class Code:
public class IsLatestAttClass {
    public static void met(List<Attended__c> att)
    {
Set<id> ids = new Set<id>();
        
        for(Attended__c obj:att)
        {
            ids.add(obj.STD_lookup__c);
            obj.IsFirst_Contact__c = true;
        }
 List<Attended__c>  abb =   [SELECT Name,IsFirst_Contact__c,STD_lookup__r.Name FROM Attended__c WHERE Attended__c.STD_lookup__c IN: ids];
       List<Attended__c> attlist = new List<Attended__c>();
       List<Attended__c> attlistnew = new List<Attended__c>();
        for(Attended__c obj:abb)
        {
            if(obj.IsFirst_Contact__c == true)
            {
                obj.IsFirst_Contact__c = false;
                attlist.add(obj);
                //Trigger.new.add(obj);
            }

        }
        update attlist;
    }

}
Error: When i try to update existing child records it is throwing error. (IsLatestAtt: execution of AfterInsert caused by: System.FinalException: Record is read-only Class.IsLatestAttClass.met: line 9, column 1 Trigger.IsLatestAtt: line 2, column 1)
Please can anyone help...!
Team NubesEliteTeam NubesElite
Hi Vamsi,
This is because you are in an after insert/update trigger and the records are read only in that context as they have been written, but not committed, to the database.
Unfortunately your trigger is relying on the ids of the records, which means you won't be able to use before insert as the ids won't be populated at that time (as the records haven't been written to the database at that point so while you can write to them, database generated fields aren't populated).
In this instance you'll need to clone the record (or query anew via SOQL) and make changes to the new copy of the record, then execute the update against the new copies.

Thank You
www.nubeselite.com
Development | Training | Consulting


Please mark this as solution if your problem resolved.
 
Vamsi VaddipalliVamsi Vaddipalli
Hi Team,
I tried with Before trigger and removed update attlist line, it got executed and sucessfully inserted as expected.
But problem is existing Attended__c record was not updating. Only newly inserted record is updated.