Reputation: 11
There is two object: Fund and opportunity. and opportunity object has a lookup of Fund. I've developed one trigger that sums up the total amount of all the relative opportunity and set that amount in a custom field of fund object. now a problem in my code is that whenever I try to create bulk opportunity using CSV file that contains data for multiple funds at that time it sums up the total of all fund and set that only in first record fund ID. I need a solution using Map. Thank you.
Trigger:
trigger newLeadTrigger on Opportunity (after insert , after update, after delete , after undelete) {
if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate || trigger.isUndelete)){
OpportunityCustomRollup.CountRollup(Trigger.new);
}
if(Trigger.isDelete)
{
OpportunityCustomRollup.CountRollup(Trigger.old);
}
}
Controller class:
public class OpportunityCustomRollup {
public static void CountRollup(List<Opportunity> lstOpportunity){
set<id> oppIds = new set<id>();
map<string, integer> classroomIDToDeskCountMap = new map<string, integer>();
id objrecordtypeid = [SELECT Id FROM RecordType WHERE DeveloperName ='Fund_Raising'].Id;
double amount = 0;
try {
for (Opportunity objOpportunity : lstOpportunity){
oppIds.add(objOpportunity.Fund__c);
}
Fund__c objfund = [SELECT Id, Total_opportunity_amount__c FROM Fund__c WHERE Id = :oppIds];
List<Opportunity> list_Opportunity = [SELECT Id, Amount FROM Opportunity WHERE Fund__c = :objfund.Id and StageName = 'Closed Won' and RecordTypeId =: objrecordtypeid];
for(Opportunity AmountOpportunity : list_Opportunity) {
amount += AmountOpportunity.amount;
}
objfund.Total_opportunity_amount__c = amount;
update objfund;
}
catch (Exception e) {
System.debug(e);
}
}
}
Upvotes: 1
Views: 504
Reputation: 19622
This should give you some ideas but you'll have to experiment a bit yourself. Edit your question with updated code and drop me a comment if you're still stuck.
// This is just for testing because when executing standalone apex code
// you don't have trigger.new. Modify the query as you want.
List<Opportunity> lstOpportunity = [SELECT Id
FROM Opportunity
WHERE StageName = 'Closed Won' and RecordType.DeveloperName = 'Fund_Raising'
LIMIT 10];
List<Fund__c> funds = new List<Fund__c>();
for(AggreateResult ar : [SELECT SUM(Amount) amt, Fund__c fund
FROM Opportunity
WHERE Id IN :lstOpportunity
AND StageName = 'Closed Won' and RecordType.DeveloperName = 'Fund_Raising'
AND Fund__c != null
GROUP BY Fund__c]){
Fund__c f = new Fund__c(
Id = (Id) ar.get('fund'),
Total_opportunity_amount__c = (Decimal) ar.get('amt')
);
funds.add(fund);
}
update funds;
P.S. Check this app on appexchange: https://appexchange.salesforce.com/appxListingDetail?listingId=a0N30000009i3UpEAI I'm not affiliated with them but if you're an admin it might be easier to configure it than to write code, unit tests..
Upvotes: 1