Roll Up Contact Count on Account
trigger rollupCount on Child__c (after insert, after delete)
{
List masterList = new List();
Map masterMap = new Map();
for(List mstrList : [Select id, Trigger_Rollup_Count__c from Master__c])
{
for(Master__c master : mstrList)
{
masterMap.put(master.Id, master);
}
}
if(trigger.isInsert)
{
for(Child__c child : trigger.new)
{
if(masterMap.containskey(child.Master__c)){
if(masterMap.get(child.Master__c).Trigger_Rollup_Count__c != null){
Master__c mas = masterMap.get(child.Master__c);
mas.Trigger_Rollup_Count__c = mas.Trigger_Rollup_Count__c + 1;
masterList.add(mas);
}
else{
Master__c mas = masterMap.get(child.Master__c);
mas.Trigger_Rollup_Count__c = 1; masterList.add(mas);
}
}
}
}
if(trigger.isDelete)
{
for(Child__c child : trigger.Old)
{
if(masterMap.containskey(child.Master__c))
{
Master__c mas = masterMap.get(child.Master__c);
mas.Trigger_Rollup_Count__c = mas.Trigger_Rollup_Count__c - 1;
masterList.add(mas);
}
}
}
if(masterList.size() > 0)
{
update masterList;
}
}
{
List masterList = new List();
Map masterMap = new Map();
for(List mstrList : [Select id, Trigger_Rollup_Count__c from Master__c])
{
for(Master__c master : mstrList)
{
masterMap.put(master.Id, master);
}
}
if(trigger.isInsert)
{
for(Child__c child : trigger.new)
{
if(masterMap.containskey(child.Master__c)){
if(masterMap.get(child.Master__c).Trigger_Rollup_Count__c != null){
Master__c mas = masterMap.get(child.Master__c);
mas.Trigger_Rollup_Count__c = mas.Trigger_Rollup_Count__c + 1;
masterList.add(mas);
}
else{
Master__c mas = masterMap.get(child.Master__c);
mas.Trigger_Rollup_Count__c = 1; masterList.add(mas);
}
}
}
}
if(trigger.isDelete)
{
for(Child__c child : trigger.Old)
{
if(masterMap.containskey(child.Master__c))
{
Master__c mas = masterMap.get(child.Master__c);
mas.Trigger_Rollup_Count__c = mas.Trigger_Rollup_Count__c - 1;
masterList.add(mas);
}
}
}
if(masterList.size() > 0)
{
update masterList;
}
}
Comments
Post a Comment