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
smitha vikramsmitha vikram 

Trigger to update field on parent based on related object field but based on created date

I have to write a trigger where i have a custom object in the related list of the parent opportunity object. The parent Opportunity has a comments field.
The user is allowed to create a new text under the custom object and every time a new record is created or updated the value in the parent must be replaced with the new value,

I can write a basic triiger on after insert and after udpated. Where i am not clear is the logic that a record is updated will not be the latest record created, how can the logic be added such the any record that is updated will get replaced with edited one.Kindly help me 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Smitha,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
trigger ParentUpdate on Child__c (after insert, after update) {
    Map<ID, Opportunity> parent = new Map<ID, Opportunity>();
    List<Id> listIds = new List<Id>();
    for (Child__c childObj : {
        listIds.add(childObj.ParentRelation__c); // API name of parent field in child object
    parent = new Map<Id, Opportunity>([SELECT Id, Comment_Field__c, (SELECT Id, Text_Field__c FROM Childs__r) 
                                   FROM Opportunity 
                                   WHERE Id IN :listIds]); // Childs__r is Child Relationship Name
    for (Child__c ch:{
        if(ch.Text_Field__c != null){
             Opportunity opp = parent.get(ch.ParentRelation__c);
             opp.Comment_Field__c = ch.Text_Field__c;
    UPDATE parent.values();

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Raghu NaniRaghu Nani
Hi @Khan Anas,

I saw your response, can you please confirm regarding the reference here.
You assigned the value in line no 17, so value will be updated in map varibale.

I am bit confused about when system will maintain reference and not?
smitha vikramsmitha vikram
Thank YOU for the immediate response, however, when arecord is inserted or edited and ONLY when the latest commenst record that goes by created date gets edited should the value on the opportunity get replaced.How can i achieve that?