+ Start a Discussion

trigger for Master Object field update

I have a couple of objects(Object1 and Object2) and the relation is Object1 is Master and Object2 is Detail. 

Object2 has field1 which is a Number and will be derived from a formula. Object1 has field1Total which is Number and holds the sum of Object2.field1. Unable to use Roll-Up Summary since formula has expressions in it. 

Based on any change in field1 it should be reflected in Object1.field1Total. I have used the below trigger to update master object based on the entry in detail object. But it is not working can any one guide me.

trigger Object2Trigger on Object2__c (after delete, after insert,after update) { Object2__c[] 0bj2= Trigger.new; Double Total = 0.00; String o1Id = obj2[0].object1_Id__r.Id; for(Object__c o2:[Select b.field1__c From Object2__c b where b.object1_Id__r.Id= : o1Id]) { Total+=o2.field1__c; } List<Object1__c> toUpdate = new List<Object1__c> {}; for(Object1__c o1:[Select e.Id,e.field1Total__c From Object1__c e where e.Id = : o1Id]) { toUpdate.add(new Object1__c(Id = o1.Id, field1Total__c =Total)); } if(toUpdate.size() > 0){ update toUpdate; } }





I recommend adding System.debug logs in your apex code and then re-run the scenario. You can output the debug statements in the System Logs or Debug Logs.