Trigger for display or update account field after creating a related contact record

Here I am going to create a trigger that update value of TotalAmount field on Account object after creating a contact record.

Requirement--

1. create a currency type field name TotalAmount on Account object.
2. create two currency type field name AmountX and AmountY on Contact object.

Scenario--

When we create or update a contact record with providing value of above created field then total value of AmountX and AmountY displays on TotalAmount field on Account object.

Trigger--

trigger TotalAmount on Contact (after insert,after update) {
    
    set<Id> ids = new set<Id>();
    for(Contact c : Trigger.new)
    {
        if(c.AccountId != null){
            ids.add(c.AccountId);
        }
    }
    
    List<Account> acList = [select id,TotalAmount__c,(select id,AmountX__c,AmountY__c from contacts) from account where id IN: ids];
    List<Account> updateToList = new List<Account>();
    
    for(Account a : acList)
    {
        for(Contact ct : a.contacts)
        {
           a.TotalAmount__c = ct.AmountX__c+ct.AmountY__c; 
           updateToList.add(a);
        }
    }
    update updateToList;

}

Comments

Popular posts from this blog

How to show or hide a particular section of Visualforce Page dependent upon picklistfield value

Process Automation Specialist Superbadge

Dynamically Add/Delete rows in Visualforce Page