You need to sign in to do that
Don't have an account?
Phuc Nguyen 18
Apex Class to Update Parent when child record created
Hello all,
I have a trigger to update a field on the Account when a note is created but I having trouble converting my trigger into a Class.
I have a trigger to update a field on the Account when a note is created but I having trouble converting my trigger into a Class.
trigger UpdateAccWithLastNote on Note (before insert) { /* List<Account> actLstToUpdate=new List<Account>(); if(Trigger.isInsert){ for(Note nt : Trigger.new){ if(String.valueOf(nt.parentId).startsWith('001')){ Account acc = new Account(Id=nt.parentId,Last_Note__c=nt.Body); actLstToUpdate.add(acc); } } } if(!actLstToUpdate.isEmpty()){ try{ update actLstToUpdate; }catch(DmlException de ){ System.debug(de); } } */ }
Please try below code:
Trigger code:
Apex class code:
Hope this helps! Please mark as best if it does.
Thanks
All Answers
Please try below code:
Trigger code:
Apex class code:
Hope this helps! Please mark as best if it does.
Thanks
Thank you, this is spot on and I and probably others appreciate the comments within the class. Could the class be expanded for Updates? So for example what if I need to get a count of all of the notes associated to an Account? Or should this be done in a seperate Class?
Thanks,
P
The same trigger works in before update case and might need slight changes for after update case. And to count all notes associated to an account you might after insert context. This can be done by adding context variables in same trigger and different function call within sameclass.
This might look like :
So you will add method CountNotesAttached for existing class and update the field in which you are keeping track
Hope this helps!
Thanks
There iseems to be plenty of examples of Triggers with roll up to parents but not classes. Interesting since I thought I trigger per object was best practice, I would assume there would be more Apex Class examples.
Cheers,
P