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
Akshay ShrivastavaAkshay Shrivastava 

by child field i want to update parent and grandparents fields

Object “P” => Detail to “Contact” MD Relationship
If we get phone number on “P” it should update with same Phone number on Contact and Account Phone number field as well.
Best Answer chosen by Akshay Shrivastava
CharuDuttCharuDutt
Hii  Akshay Shrivastava
Try The Below Code
trigger fieldupdatefromchild on CustomObject__c (before insert) {
    List<Account> accList=new List<Account>();
    List<Contact> conList=new List<Contact>();
    String setPhone;
    Set<Id> setConIds = new Set<Id>();
    Set<Id> setAccIds = new Set<Id>();
    If(Trigger.IsInsert && Trigger.IsBefore){
        for(CustomObject__c tr : trigger.new){
            setPhone = tr.Phone__c;
            setConIds.add(tr.Contact__c);
        }
    }
    
    for(contact conToUpdate : [Select Id,Name,AccountId from Contact where Id =:setConIds ]){
       conToUpdate.Phone = setPhone;
        setAccIds.Add(conToUpdate.AccountId);
        conList.add(conToUpdate);
    }
    for(Account accToUpdate: [select Id,Name From Account Where Id = :setAccIds]){
        accToUpdate.Phone = setPhone;
        accList.Add(accToUpdate);
    }
    if(acclist.size()>0){
        update accList;     
    }
    if(conList.size()>0){
        update conList;     
    }
}
Please Mark It As Best Answer If It Helps
Thank you!