+ 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!