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
SFUserSFUser 

Update Parent Record Fields when Child record is change its parent value

I have 2 Objects..i.e. Parent & Child objects.
In Parent Object.., i have 2 fields..numberOfRecords__c & Total_Amount__c.
In Child Object.., i have 2 fields..Parent__c(lookup to Parent__c) & Amount__c.
Now my requirement is whenever the child record is changes to another new Parent record..
then i want to update Both (numberOfRecords__c & Total_Amount__c) fields for new Parent record.
Suggest any code.
Thanks in Advance.
CharuDuttCharuDutt
Hii Sukumar
Try Below Code
If You Don't Want To Code You Can Use Roll-up Summary Field But Make Sure Object Have Master-detail Relationship
trigger NumberOfChild2 on Contact (After Insert,After Update,After Delete) {
List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
    if(Trigger.isInsert){
         if(trigger.isAfter){
        for(Contact con : Trigger.new){
            if(con.AccountId != null){
            setAccIds.add(con.AccountId);
            	}
			}
		}
    } 
    system.debug('setAccIds ==> '+setAccIds);
    if(Trigger.isUpdate){
         if(trigger.isAfter){
        for(Contact con : Trigger.new){ 
            if(con.AccountId!=Trigger.oldMap.get(con.Id).AccountId ||                                    
               con.Amount__c!=Trigger.oldMap.get(con.Id).Amount__c){
               	setAccIds.add(con.AccountId);
                setAccIds.add(Trigger.oldMap.get(con.Id).AccountId);
            	}
          
			}        
        }
    }
    if(Trigger.isDelete){
        if(trigger.isAfter){
        for(Contact con : Trigger.old) { 
            if(con.AccountId != null){
            setAccIds.add(con.AccountId);
            	}
        	}
        }
    }    
    for(Account acc :[Select id,Total_Records__c,Total_Amount__c ,(Select id,name,Amount__c from contacts) from Account where Id in : setAccIds]){
			integer val = 0;
        for(Contact con : acc.Contacts){
            
            val += integer.valueOf(con.Amount__c);
            system.debug('====> ' +val);
        }
        system.debug(val);
        acc.Total_Amount__c = string.valueOf(val);
        acc.Total_Records__c = acc.contacts.size();
        acclist.add(acc);
        
    }
    if(acclist.size()>0){
        update accList;     
    }
}
Please Mark It As Best Answer If It Helps
Thank You!