You need to sign in to do that
Don't have an account?
Vempally
need help with the following trigger
Hi everyone...
In the for loop where iam retrieving contacts based on an account, when SOQL is used its working fine but when the soql is replaced with a a.contacts the for loop is not getting executed... Why...?
trigger CustomRollupSummary on Contact (after insert, after update, after delete, after undelete) { if(trigger.isInsert && Trigger.isAfter){ List<Account> lst_accounts = new list<Account>(); //decimal Value =0; set<id> account_ids = new set<id>(); for(Contact c : trigger.new){ account_ids.add(c.accountid); system.debug('account_ids' + account_ids); } Map<id, Account> map_accounts = new Map<id, Account>([select id, name from Account where id in : account_ids]); system.debug('map_accounts' + map_accounts); system.debug('map_accounts' + map_accounts.values()); for(Account a : map_accounts.values()){ system.debug('account' + a); a.Amount_Sum__c = 0; //for(Contact c :[select id, name, amount__c from contact where accountid =: a.Id]) for(Contact c : a.contacts) { system.debug('Contact' + c); a.Amount_Sum__c += c.amount__c; } lst_accounts.add(a); } system.debug('updated accounts' + lst_accounts); update lst_accounts; } /* List<Contact> lst_contacts = new List<Contact>(); for(Account a : lst_account){ lst_contacts.add(a.contacts); system.debug('lst_contacts'); */ }
In the for loop where iam retrieving contacts based on an account, when SOQL is used its working fine but when the soql is replaced with a a.contacts the for loop is not getting executed... Why...?
when you are fetching accounts, you need to use relationship query to have contacts. I have added relationship query in your code so thats your map_accounts wil hold all related contacts as below
Map<id, Account> map_accounts = new Map<id, Account>([select id, name,(select amount__c,id from contacts) from Account where id in : account_ids]);
please check this and let me know if it helps you.
Thanks,
Debasis
If i have understood your trigger in correct way then I think you camn use below code for it. We no need to fire another query to fetch the account to update its amount_sum__c field.
please use this optimized code and let me know if it helps you.
Please find the below trigger:
Here I handled:
(1) Corrected the Logic.
(2) Naming convention.
(3) Alignment.
(4) Considered all possible scenarios.
(5) Tested the solution in my DE environment and looks good.
Above trigger will not work if you modify the Account on the Contact. When we modify the Account on Contact we have to re-calculate the Rollup summary on both new and old Accounts.
Please do let me know if it helps you.
Regards,
Mahesh
Please try the below sample code.
Hope this helps you!
Best Regards,
Jyothsna
How to find min, max values...?