I have a custom object Booking__c which has a Related List of a custom object Notes__c. I want to reuse useful Notes for new Bookings as if any existing Note could be a template. On Notes__c I have fields Name, Visibility__c, Note__c(text area), Booking__c(lookup to Booking__c), Template(lookup to Notes__c). When Template__c is populated with an existing Note, I want to populate all the new Notes fields with the existing Note.
With the code below, i'm receiving an error:
populateNotefromNoteTemplate: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.populateNotefromNoteTemplate: line 21, column 1
Here is my code:
trigger populateNotefromNoteTemplate on Note__c (before insert , before update) {
if(trigger.isbefore && trigger.isinsert)
{
Set<ID> NoteIds = new Set<ID>();
for(Note__c note : trigger.new)
{
NoteIds.add(note.Template__c);
}
list <Note__c> notelist = [SELECT ID, Name, Visibility__c, Note__c FROM
Note__c WHERE ID IN:NoteIds];
MAP<ID , Note__c> mapNote = new MAP<ID , Note__c>();
for(Note__c n : Notelist)
{
mapNote.put(n.id, n);
}
for(Note__c note : trigger.new)
{
if(trigger.oldmap.get(note.Id).Template__c != note.Template__c){
if(note.Template__c!=null)
{
if(mapNote.containskey(note.Template__c))
{
Note__c n = mapnote.get(note.Template__c);
note.Name = n.Name;
note.Visibility__c = n.Visibility__c;
note.Note__c = n.Note__c;
}
}
else
{
note.Name = null;
note.Visibility__c= null;
note.Note__c = null;
}
}
}
}
}