Hello Replace trigger code with below code:
Also made some changes in class code as :trigger AvgUtilityTrigger on Utility__c (after insert, after update, after delete) {
if( Trigger.isInsert || Trigger.isAfter || Trigger.isDelete ){
if( Trigger.isAfter ){
AvgUtility.avgUtility();
}
}
}
Try these codes and let me know the results.Thanks and RegardsAyushpublic class AvgUtility {
public static void avgUtility (){
Set<Id> propertyIds = new Set<Id>();
List<Property__c> propertyToUpdate = new List<Property__c>();
List<Utility__c> utilities = Trigger.isInsert || Trigger.isUpdate ? Trigger.New : Trigger.Old;
for( Utility__c ut : utilities ){
propertyIds.add( ut.Property__c /*lookup field value of utilityrecord */ );
}
for( AggregateResult ag : [ SELECT Property__c, AVG( Amount_Paid__c ) avg FROM Utility__c
GROUP BY Property__c ] ){
propertyToUpdate.add( new Property__c(
Id = (Id)ag.get('Property__c'),
Average_Utility__c = (Decimal)ag.get('avg') ) );
}
if( propertyToUpdate.size() > 0 ){
update propertyToUpdate;
}
}
}
4 risposte