+ Start a Discussion
Annabelle BlackburnAnnabelle Blackburn 

Apex trigger for update of a child field on a parent object

Hi there,
I have a custom object called Whitepapers (WP), and its child custom object called Whitepaper Downloads (WPD). On my WPD I have a field called Date Downloaded. I would like to add a field to WP that displays the latest WPD Date Downloaded.
I believe I need an apex trigger for this because formulas don't reach up that way on custom objects. Any ideas on what that trigger would look like?
Thanks for your help!
Annabelle
Nitin SharmaNitin Sharma
Hi Annabelle,

You can achive this wihout coading . Use process builder for that. Create a field on parent object and match this field with Data Downloaded feld on Whitepaper Download object.
See below link it will help you.
https://developer.salesforce.com/trailhead/force_com_admin_intermediate/business_process_automation/process_builder

Thanks,
Nitin Sharma
 
Annabelle BlackburnAnnabelle Blackburn

Hi Nitin,

Thanks for your suggestion! I'm a big fan of using Process Builder but unfortunately it's limited in the sense it will only update fields if the record is changed. I would like this to happen automatically, regardless of whether the parent record is changed. I believe an Apex Trigger is the only way I can achieve that.

Thanks,
Annabelle

Nitin SharmaNitin Sharma
Hi Annabelle,
According to your scenario use below trigger.  Create a WPD_Date_Downloaded__c  on Whitepaper__C object  And use this trigger.
 
trigger UpdateWPD on Whitepaper_Download__c (after insert, after update) {
  Map<ID, Whitepaper__c> parentObj = new Map<ID, Whitepaper__c>();
  List<Id> listIds = new List<Id>();

  for (Whitepaper_Download__c  childObj : Trigger.new {
    listIds.add(childObj.Date_Downloaded__C);
  }

  
  parentObj = new Map<Id, Whitepaper__C>([SELECT id, WPD_Date_Downloaded__C ,(SELECT ID, Date_Downloaded__C FROM Whitepaper_Download__r) FROM Whitepaper__c WHERE ID IN :listIds]);

  for (Whitepaper_Download__C wpd : Trigger:new){
     Whitepaper__c myParentObj = parentObj.get(wpd.Whitepaper__c);
     myParentObj.WPD_Date_Downloaded__C = wpd.Date_Downloaded__c;
  }

  update parentObj.values();
}

 
Annabelle BlackburnAnnabelle Blackburn

Hi Nitin,
Thanks for typing that out. Would this only target the latest date? For example Whitepaper A was downloaded by Jo on the 29th of March and by Jane on the 23rd of March. I would want Jo's Date Downloaded to appear in that field, even if Jane was added to the record after Jo.

I will try this piece of code as it is now and see if it works! Thanks Nitin
Annabelle