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
dowzydowzy 

Calculate field value present in a contact into a account

Hi All,

There is a field name "Rating" in my contact .
eg:  Account "Abc" with 3 contact 'x', 'y', 'z'
i want to calculate rating field present in this 3 contact and to make it an
average. and display it on account

Can this be possible

Need your help on this

Thanks in advance.

Regards,
Samuel

hitesh90hitesh90

Hi,

 

You have to write Trigger on Contact object to fulfill your requirement.

 

see below sample trigger as per your requirement.

 

Apex Trigger:

trigger tskUpdateAccRatingtrigger on Contact(after insert, after update,after delete) {
    List<Contact> lstContact = [select id,AccountId from Contact where id in: trigger.newmap.keyset()];
    set<Id> sAccId = new set<Id>();
    for(Contact t: lstContact){
        if(t.AccountId != null){
            sAccId.add(t.AccountId);
        }
    }
    if(sAccId != null && sAccId.size() > 0){
        List<Account> lstAccount = [select id, (select id,Rating__c from Contacts) from Account where id in: sAccId];
        if(lstAccount.size() > 0){
            for(Account acc: lstAccount){
                Decimal decrating = 0;
                Integer intSumRating = 0;
                for(Contact con: acc.Contacts){
                    intSumRating += Integer.valueOf(con.Rating__c);
                }
                if(acc.Contacts.size() > 0){
                    decrating = decimal.valueOf(intSumRating/acc.Contacts.size());
                }
                acc.Averate_ContactRating__c = decrating;
            }            
            update lstAccount;
        }
    }
}

 

 

 

Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator
My Blog:- http://mrjavascript.blogspot.in/