1

I want to write a trigger on 'Note' object, what the trigger should do is:-

  1. I have a object called Incident__c and a custom field called Notes__c (Long Text Area).
  2. Whenever a Note get created(In the Incident__c object record), Notes__c field should be updated with Note body.
  3. When there are many Notes created, Notes__c field should append with all Note bodies.
  4. Also, when an existing 'Note' is edited, edited value should be updated in the Notes__c field.

My code provided below is doing what I want.

I want to update the Notes__c field, when a 'Note' is deleted. How can I do this? I am bit confused because how does the field know which bit to remove ?

-----Helper class--------------
public with sharing class NoteTriggerHelper {
    public static void insertNotesBodyToTextField(List<Note> notes){
        Set<Id> incid = new Set<Id>();
            for(Note n : notes){
                incid.add(n.ParentId);
            }

        List<grc__Incident__c> incidents = [Select Id,Notes__c, (SELECT Id,Title, Body FROM Notes) from grc__Incident__c where Id IN :incid];

            for(grc__Incident__c incident : incidents){
                incident.Notes__c = getNotesString(incident.Notes);
            }

        update incidents;
    }


    private static String getNotesString(List<Note> notes){
        String notesString = '';

            for(Note nt : notes){
                notesString = ' seperator ' + nt.Body + '\n' +notesString;
            }
                return notesString;
    }
}

-----------Trigger--------------
trigger NoteTrigger on Note (after insert, after update) {
    if(Trigger.isAfter){
        if(Trigger.isInsert){
            NoteTriggerHelper.insertNotesBodyToTextField(Trigger.new);
        }

        if(Trigger.isUpdate){
            NoteTriggerHelper.insertNotesBodyToTextField(Trigger.new);
        }
    }
}

2 Answers 2

1

This would be similar to insert trigger but with little difference.

  1. Added after delete event to Trigger

    trigger NoteTrigger on Note (after insert, after update, after delete) {
      if(Trigger.isAfter){
        if(Trigger.isInsert){
            NoteTriggerHelper.insertNotesBodyToTextField(Trigger.new);
        }
    
        if(Trigger.isUpdate){
            NoteTriggerHelper.insertNotesBodyToTextField(Trigger.new);
        }
        if(Trigger.isDelete)
            // Do your stuff here
        }
      }
    }
    
  2. Collect parent Id same as you are collecting in insert trigger

  3. Query the field of the object using the collected parent ID
  4. Populate the required field and update the list.
1

You can simply do it using the Process Builder.

Try it if you can, you don't need to write the big coding and it is very easy to understand also.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .