Roll up Amount from Child Object To Parent Object in Case of Lookup Relationship

Case: Roll up the values from Child to Parent Object in Case of Lookup Relationship.
On Child Object (ChildObjectApiName__c) there is custom field Amount__c
On Parent Object(ParentObjectApiName__c) there is a custom Field TotalChildAmount__c
On Child Object relation ship of Parent Object is ParentObjectRealtionShipApiName__c



Trigger triggerName on ChildObjectApiName__c(aftet insert, after delete, after update, after undelete)
{
set<id> setofParentObjectID = new set<id>(); // Storing the parent object Ids

map<Id, ParentObjectApiName__c> mapofParentObjectIdToParnetObject  = new Map<Id, ParentObjectApiName__c>(); // Map is used for Storing the Parent Record Id to Parent Object

if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
{
for(ChildObjectApiName__c objChildObject1: trigger.new)
{
if(objChildObject1.ParentObjectRealtionShipApiName__c != null)
{
setofParentObjectID.add(objChildObject1.ParentObjectRealtionShipApiName__c);
}
}
}

if(Trigger.isdelete)
{
for(ChildObjectApiName__c ChildObject2 : trigger.old)
{
if(ChildObject2.ParentObjectRealtionShipApiName__c != null)
{
setofParentObjectID.add(ChildObject2.ParentObjectRealtionShipApiName__c);
}
}
}

if(setofParentObjectID != null && setofParentObjectID.size()>0)
{
for(ID eachParentObjectId : setofParentObjectID)
{
mapofParentObjectIdToParnetObject.put(eachParentObjectId, new ParentObjectApiName__c(ID = eachParentObjectId, TotalChildAmount__c =0);
}

for(ChildObjectApiName__c ChildObj:[Select Id, ParentObjectRealtionShipApiName__c, Amount__c from ChildObjectApiName__c where ParentObjectRealtionShipApiName__c IN:setofParentObjectID){
mapofParentObjectIdToParnetObject.get(ChildObj.ParentObjectRealtionShipApiName__c).TotalChildAmount__c += Amount__c;

}
}
if(mapofParentObjectIdToParnetObject != null && mapofParentObjectIdToParnetObject.size()>0)
{
update mapofParentObjectIdToParnetObject.Values();
}

}

Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page