function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mohan s 37mohan s 37 

how to delete the parent field values when deleting the child field values

hi friends,

               The following code is not working for delete event in trigger. But it's working fine for after insert and after update events.
I have custom object Revenue__c. It has master detail relationship with Account. I want to update Account field values with revenue field values whenever the revenue is inserted,updated and deleted.Can any one suggest me what is the wrong in the following code
trigger revenuetrigger on Revenue__c(after insert, after update,after delete){
if(trigger.isinsert || trigger.isupdate ){
new RevenueCal().populateRevenu(trigger.new);
}if(trigger.isdelete){
new RevenueCal().populateRevenu(trigger.old);
}
}
Apex class:
public class RevenueCal {
    Map<Id,Account> accmap = new Map<Id,Account>();
   public List<Id> ids = new List<Id>(accmap.keySet());
    public List<Account> childsToupdate = new List<Account>();
    //ids.addAll();
   public map<String,Revenue__c> linkIdMap = new Map<String,Revenue__c>();
    List<Account>listToUpdate = new List<Account>();
    public void populateRevenue(List<Revenue__c> revlist){
        for(Revenue__c rev : revlist){
           linkIdMap.put(rev.Reporting_Link_Id__c, rev);
          
        }
        //update listToupdate;
        for(Account a : [SELECT Id, Name,Link_Id__c,ParentId,Reporting_Link_Id__c,Revenue_Product__c,
                         Revenue_Service__c,Revenue_Cloud__c FROM Account]){
            if(linkIdmap.containsKey(a.Reporting_Link_Id__c)){
                a.Revenue_Product__c = linkIdmap.get(a.Reporting_Link_Id__c).Product_Revenue__c;
                a.Revenue_Service__c = linkIdmap.get(a.Reporting_Link_Id__c).Service_Revenue__c;
                a.Revenue_Cloud__c = linkIdmap.get(a.Reporting_Link_Id__c).Cloud_Revenue__c;
                childsToupdate.add(a);
            }
        }
        try{
        update childsToupdate;
        }Catch(Exception e){
            system.debug('update failes due to:'+e.getMessage());
        }
    }
}
GauravendraGauravendra
Hi mohan,

In case of delete you are not doing anything different, you just updating the account field value with old revenue obj value.
I think you need to set the values to zero in case of delete.

Like  a.Revenue_Product__c =0; (considering Revenue_Product__c field is of Number data type)
and then update the account records.

Hope this helps.