You need to sign in to do that
Don't have an account?
Priyanka7
sum a field of contact and show in account without using aggregate function
Hi,
I have a number field in Contact and i want to show the sum of the number field for each contact in Account. How should I use without aggregate function?
You may use trigger refer sample code.
Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
Best Regards
Sandhya
All Answers
You may use trigger refer sample code.
Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
Best Regards
Sandhya
Above code is not work for the update and delete events ..
I have shared a sample code. It will works well
trigger rollAmountwithoutAggregate on Contact (after insert,after update,after delete,after undelete)
{
set<id> setids = new set<id>();
list<Account> acclist = new list<schema.account>();
list<Account> accuplst = new list<schema.account>();
list<Account> accdellst = new list<schema.account>();
decimal sum;
if(trigger.isinsert )
{
for(contact c : trigger.new)
{
setids.add(c.Accountid);
}
}
if(trigger.isUndelete)
{
for(contact c :trigger.new)
{
setids.add(c.Accountid);
}
}
for(Account ac : [select id,name,RollupAmount__c,(select id,name,conAmount__c from contacts)from Account where id In:setids])
{
sum = 0;
for(contact ct : ac.contacts)
{
sum += ct.conAmount__c;
}
ac.RollupAmount__c = sum;
acclist.add(ac);
}
if(acclist.size()>0)
{
update acclist;
}
if(trigger.isupdate)
{
for(contact c : trigger.old)
{
Account ad = [select id,name,RollupAmount__c from Account where id=:c.accountid];
list<contact> clst = [select id,name,conAmount__c from contact where accountid=:ad.id];
sum = 0;
for(contact ct1 : clst)
{
if(ct1.conAmount__c!=null)
{
sum += ct1.conAmount__c;
}
}
ad.RollupAmount__c = sum;
accuplst.add(ad);
}
update accuplst;
}
if(trigger.isDelete)
{
for(contact c : trigger.old)
{
setids.add(c.Accountid);
}
for(Account at : [select id,name,RollupAmount__c,(select id,name,conAmount__c from contacts)from Account where id In:setids])
{
for(contact c : trigger.old)
{
at.RollupAmount__c -= c.conAmount__c;
accdellst.add(at);
}
}
update accdellst;
}
}
Hi sandhaya,
the code which you have written in that you are doing nested loop can we do in single loop without using any sum() function