Skip to main content
Hello Friends,

I am trying to write an apex trigger that will update a custom field on the account called "Most recent Note". I found an old thread an altered code I found there to get:

trigger updateAccountField on Note (after insert, after update) {

 List<Account> accUpdate = new List<Account>();

    for(Note n : Trigger.new){

        if(n.ParentId != null && n.ParentId.getSObjectType() == Account.sObjectType && n.Title.Contains('Client Health')){

            Account acc=new Account(Id=n.parentId,Most_recent_Note__c=n.LastModifiedDate);

            accUpdate.add(acc);

       } 

    }

    

    if(accUpdate.size()>0){

        update accUpdate;

    }

}

This code works the classic notes and attachments but I am struggling to replicate it for lightning notes. I know I have to use the ContentVersion object but am running into issues there. I would appreciate any help or suggestions on this issue!
1 件の回答
  1. 2020年3月31日 15:39
    Hi Evan,

    Please give a try with below code. It worked for me when I attached note to Account using "New Note" in both classic and lightnning and tested in my org. 

    trigger updateAccountField on Note (after insert, after Update) {

    set<id> Accountids=new set<id>();

    list<Account> accUpdate =new list<Account>();

    for(Note n:Trigger.New){

    // Gathering all the Account Ids to which notes are attached

    if(String.valueOf(n.parentId).startsWith('001') && n.Title.Contains('Client Health')){

    Accountids.add(n.parentId);

    }

    }

    if(Accountids.size()>0){

    accUpdate =[Select id,Most_recent_Note__c from Account where id in :Accountids];

    }

    // Comparing with note id and Account id and updating the Last_Note__c field wit note body

    for(Note nt : Trigger.new){

    for(integer i=0;i<accUpdate.size();i++)

    {

    if(nt.parentId==accUpdate.get(i).id)

    {

    accUpdate.get(i).Most_recent_Note__c= nt.LastModifiedDate;

    }

    }

    }

    if(!accUpdate.isEmpty()){

    try{

    update accUpdate;

    }catch(DmlException de ){

    System.debug(de);

    }

    }

    }

    Hope this helps! Please mark as best if it solves your problem.

    Thanks
0/9000