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
Ankit KhuranaAnkit Khurana 

how to populate child roll up without having master detail?

there is custom field Amount Iin contact and account.i need to find roll up of sum of all contact amount in account amount also any changes in contact should make changes in the amount of account.Since roll up can only be made in master-detail and account -contact are lookup .therefore i have written a trigger using aggregate function,but its not working Please help

trigger accountupdate on Contact (after insert,after update,after delete)
{
for (Contact con:trigger.new)
{
Account ac=[Select Amount__c,Account.name from Account where Account.name =:con.Account.name];
AggregateResult[] amountsum=[Select SUM(Amount__c)s from Contact where Account.name=:con.Account.name];
object acc=amountsum[0].get('s');
system.debug('aaaa'+acc);
//ac.Amount__c=acc[0];
// update ac;
}
}

~Onkar~Onkar

Hi Ankit,

 

Try this code May be it will resolve your problem.

 

This is trial code and support bulk data as well need to check some aggregate limitation.

 

trigger accountupdate on Contact (after insert,after update,after delete)
{
    Set<Id> accountIdset = new Set<Id>();
   
    for (Contact con:trigger.new)
    {
       accountIdset.add(con.AccountId);
    }
    Map<Id,Account> AccountMap = new Map<Id,Account>([Select Id,Amount__c from Account where Id in :accountIdset]);
    for(AggregateResult res : [SELECT AccountId, SUM(Amount__c) cnt FROM Contact where AccountId in : accountIdset GROUP BY ROLLUP(AccountId)]){
        if(res.get('AccountId') <> null){
            AccountMap.get((ID)res.get('AccountId')).Amount__c = (Decimal)res.get('cnt');
        }
    }
    update AccountMap.values();
}

 

Please accept as solution if it solve your problem.

 

Thanks

Onkar

Ankit KhuranaAnkit Khurana
thanks.....it worked!!!! Thanks and Regards, Ankit khurana Associate IT Consultant, ADIG FUJITSU CONSULTING INDIA Office: 26734 India Mobile: +91 8600960831 E-mail: Ankit.khurana@in.fujitsu.com U.S. Toll Free: (+1) 866-573-4404 shaping tomorrow with you 7 Switch off as you go | q Recycle always | P Save Paper - Save Trees |
~Onkar~Onkar

Please suggest this as solution.