I have a requirement on Trigger and scenario is given below
I created a field called amount on Account and contact objects. Later i created a record for account called AAA where amount value is nothing. Under this account record AAA, i created two contacts records named CCC1 and CCC2 with amount value is some x1 and x2 respectively.
After creating this contacts under this account record, i need to update the record AAA amount value with sum of x1 and x2. Like this, if i create one more contact record CCC3(Let say) under AAA, then amount value of account record should be updated with sum of x1+x2+x3. Likewise if i delete one contact record from AAA, then amount for AAA is should be sum of remaining contacts and vice versa for if i update contacts amount values.
To do this, I developed the following trigger.
Trigger Amount_Total_on_Contact on Contact (after insert) {
List<Account> acc1 = new List<Account>();
List<Account> acc = [select Amount__c,(select AccountId from contacts where AccountId in:Trigger.OldMap.keySet())from account];
AggregateResult results=[select sum(Amount__c)total from Contact where AccountId in:Trigger.newMap.keySet()];
for(Contact cc: Trigger.New) {
for(Account a: acc) {
a.Amount__c = (Decimal)results.get('total');
acc1.add(a);
}
}
update acc1;
}
But my problem in this trigger is, amount value of account record is not reflecting.
Note: Its is not mandatory for using after insert event. I just took it for checking. we can add other events like update and delete.
Please help me out from this problem.