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
Phuc Nguyen 18Phuc Nguyen 18 

Method to update Parent record after child deleted

Hello,
I have a class that updates a field on the Acocunt object when a Note is inserted or updated.  I am having an issue on Delete. 
If a Note is deleted I want to grab the remining Note with the most recent LastModifiedDate.  I would use the body in this note to update the field on the Accoun the record.   But I am not able to get that record.  I just keep querying the record that is being deleted.  So the Account field is never updated.  And if there are no remaining noted I want the Account field to be null.  
Thanks,
P
Best Answer chosen by Phuc Nguyen 18
SarvaniSarvani
Hi Phuc,

Glad that your trigger worked. Please try with below test class it should cover 100% . In case of further help on test class please try to create new thread.
@isTest public class UpdateAccountNoteTestClass {

 @isTest public static void TestMethodNotedelete(){
        
   /* Test data with Account having only one note attached*/ 
     
     Account Acc=new Account();
     Acc.name='Test Account with one Note ';
     Insert Acc;
     Note newnote= new NOte();
     newnote.title='Test Note Sample';
     newnote.ParentId=Acc.id;
     newnote.Body='This is the body of note';
     Insert newnote;     
    
     /* test data Account having 2 notes attached */
     Account Acc1=new Account();
     Acc1.name='Test Account with two Notes ';
     Insert Acc1;
     Note newnote2= new NOte();
     newnote2.title='Test Note Sample1';
     newnote2.ParentId=Acc1.id;
     newnote2.Body='Note 2';
     insert newnote2;
     Note newnote3= new Note();
     newnote3.title='Test Note Sample2';
     newnote3.ParentId=Acc1.id;
     newnote3.Body='Note 3';
     Insert newnote3;
     
     /* test data is ready Trying to delete notes attached to each of the account */
     test.startTest();
     Delete newnote;
     Delete newnote3;
     test.stopTest();
    }
}
Hope this helps!

Thanks

All Answers

SarvaniSarvani
Hi Phuc,

Add to your existing code with additional after delete criteria like below:

Trigger Code:
trigger UpdateAccWithLastNote on Note (before insert, before update,after delete) {
      // Add this code to existing 
    if(Trigger.isAfter && Trigger.isDelete)
    {
      UpdateAccountNoteClass.Afterdelete(Trigger.old);  
    }
       
   }
Apex class with name UpdateAccountNote and class afterdelete. You can also add only Afterdelete() method to your existing class if you want to avoid many classes.
public class UpdateAccountNoteClass {
   
    public static void Afterdelete(list<Note> deletednotes){
         
         set<id> Accountids=new set<id>();
        set<id> searchaccountids=new set<id>();
        list<Account> AccountswithNoNotes=new list<Account>();
         Map<id, string> AccountwithNotes=new Map<Id, string>();
        
// Collecting the accountids of deleted notes
        
        for(Note x:Deletednotes){
            if(String.valueOf(x.parentId).startsWith('001')){
			Accountids.add(x.parentId);    
        }
    }
        
        
        // To verify if there are any Notes attached to account (Validating if there is atleast one note attached after deleting the note) 
        list<Account> accs=    [select id,testfield__c,(select id from notesandattachments) from Account where id in:Accountids];
        
        for(Account a:accs){
            if(a.notesandattachments.size()>0){
                searchaccountids.add(a.id);
            }
            //if there are no more notes attached after delete the custom field on account is updated with null value
            else{
                a.testfield__c='';
                AccountswithNoNotes.add(a);
            }
        }
        if(AccountswithNoNotes.size()>0){
            Update AccountswithNoNotes;
        }
        
       
       
       // if there is atleast one note after delete, then update the account field with notes body which is last modified. 
        if(searchaccountids.size()>0){
            for(id x: searchaccountids){
               Note notestosameAccount= [select id, parentid, createddate,body from note where parentid =:x order by lastmodifieddate desc limit 1];
                if(notestosameAccount!=NULL){
                     // Storing the key as account id and note body to value 
                AccountwithNotes.put(notestosameAccount.ParentId, notestosameAccount.body);
                }
                
            }
        }
        if(!AccountwithNotes.isEmpty()){
            Account[] updateAccounts = new Account[] {};
            for (Id id : AccountwithNotes.keySet()) {
                updateAccounts.add(new Account(Id = id, TestField__c = AccountwithNotes.get(id)));
            }
			update updateAccounts;
             }
         }
}

Hope this helps! Please mark as best answer if it does.

Thanks
Phuc Nguyen 18Phuc Nguyen 18
Thank you very much Sarvani for the reply.  Still not seeing the value from the Note  with the most recent last modified date after a delete. I am going to add some system debugs into the code and see if anything turns up.

Cheers,
P
Phuc Nguyen 18Phuc Nguyen 18
Hey Sarvani,
All of the Notes are atatched to a single Account record so do I need pass the a list
list<Note> deletednotes
Thanks,
P
 
Phuc Nguyen 18Phuc Nguyen 18
Hey Sarvani,
I think I got it,  Would you be able to assist with some test class code coverage or do you want me to create a new post?
No coverage in these lines:
Note notestosameAccount= [select id, parentid, createddate,body from note where parentid =:x order by lastmodifieddate desc limit 1];
                if(notestosameAccount!=NULL){
                AccountwithNotes.put(notestosameAccount.ParentId, notestosameAccount.body);
                }
                
            }
        }
   
            Account[] updateAccounts = new Account[] {};
            for (Id id : AccountwithNotes.keySet()) {
                updateAccounts.add(new Account(Id = id, TestField__c = AccountwithNotes.get(id)));
            }
			update updateAccounts;

Thank you for all of your help:
P


 
SarvaniSarvani
Hi Phuc,

Glad that your trigger worked. Please try with below test class it should cover 100% . In case of further help on test class please try to create new thread.
@isTest public class UpdateAccountNoteTestClass {

 @isTest public static void TestMethodNotedelete(){
        
   /* Test data with Account having only one note attached*/ 
     
     Account Acc=new Account();
     Acc.name='Test Account with one Note ';
     Insert Acc;
     Note newnote= new NOte();
     newnote.title='Test Note Sample';
     newnote.ParentId=Acc.id;
     newnote.Body='This is the body of note';
     Insert newnote;     
    
     /* test data Account having 2 notes attached */
     Account Acc1=new Account();
     Acc1.name='Test Account with two Notes ';
     Insert Acc1;
     Note newnote2= new NOte();
     newnote2.title='Test Note Sample1';
     newnote2.ParentId=Acc1.id;
     newnote2.Body='Note 2';
     insert newnote2;
     Note newnote3= new Note();
     newnote3.title='Test Note Sample2';
     newnote3.ParentId=Acc1.id;
     newnote3.Body='Note 3';
     Insert newnote3;
     
     /* test data is ready Trying to delete notes attached to each of the account */
     test.startTest();
     Delete newnote;
     Delete newnote3;
     test.stopTest();
    }
}
Hope this helps!

Thanks
This was selected as the best answer