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 Post

Fetch Picklist value in LWC using Schema class

Get Last day of Month

Write The Dynamic Query in Salesforce and bind in page block table with filter conditions