Custom roll up summary
By using formula field we can achieve only single records using field but roll up summary is helps to calculate value from related set of records. In order to create roll up summary their must be master detail relationship between objects and we can auto assign using roll up summary fields. It helps you to find count,sum,max,min of requested fields.
trigger to count number of contacts on account by Custom roll up summary
Business case :
As per requirement, System Administrator need to know count of associated contacts to single account.
In order to achieve requirement we can use out of box functionality with standard roll up summary or custom roll up summary, Here I am explain about Custom Roll up Summary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Custom roll up summary trigger to find count of contacts on account Trigger NumberOfContactsCounts on Contact (after insert){ Set<Id> AccountSetId = new Set<Id>(); List<Account> AccountList = new List<Account>(); List<AggregateResult> AggreList = new List<AggregateResult>(); Map<String,Double> acmap = new Map<String,Double>(); for (Contact con: Trigger.new){ AccountSetId.add(con.accountId); } if(AccountSetId.size()>0){ AggreList = [select AccountId aid,Count(Id) i from Contact where AccountId IN :AccountSetId group by AccountId]; } for(AggregateResult q : AggreList){ acmap.put((String)q.get(‘aid’),(Double)q.get(‘i’)); } for (Account acc:[Select Id,Total_Count__c From Account Where Id in: AccountSetId]){ acc.Total_Count__c = acmap.get(acc.Id); AccountList.add(acc); } update AccountList; } |
Keep visiting us for more updates No tags for this post.