+ Start a Discussion
Parvinder ChanaParvinder Chana 

Trigger to insert records to grandchild table

Hello, I need help to develop trigger to insert record to grand child table. Here is the need. 

When a new task is created, I want to add this as a note and link to the task. New notes used contentnote and contentdocumentlink tables. I developed a trigger on object task and was successfully able to insert note in but to link note to the task I need to insert record contentdocumentlink object and that is where I need help.

here is the trigger on task to insert record in note table:

trigger createNotes on Task (after insert) {
    List<ContentNote> NotesToInsert = new List<ContentNote> ();
    for (Task t : Trigger.new){
        if (t.Status_Update__c == 'insert note') {  
        ContentNote n = new ContentNote (); 
        n.Title = 'Inserted from Task'; // using fixed value for testing
        n.Content = Blob.valueOf(t.Status_Update__c.escapeHTML4()); 
        }//end if
    }//end for o
    //once loop is done, you need to insert new records in SF
    // dml operations might cause an error, so you need to catch it with try/catch block.
    try {
        insert NotesToInsert; 
    } catch (system.Dmlexception e) {
        system.debug (e);
The next step is to insert into ContentDocumentLink, here is what need to inserted

ContentDocumentLink.ContentDocumentId will be ContentNote.Id from notes table
ContentDocumentLink.LinkedEntityId will be task.Id from task table
ShareType will be "V" //fixed value
Visibility vill be "AllUsers" //fixed value

The one way could be write a trigger on Contentnote which I don't want since data in ContentNote will be coming from other areas in Salesforce as well.

Look forward to hear from experts.

Thanks in advance,
deepak balur 19deepak balur 19
I think you can proceed as below:List<ContentDocumentLink> CDLInsert = new List<ContentDocumentLink> ();
for (ContentNote CN: NotesToInsert ){

  ContentDocumentLink CDL = new ContentDocumentLink (); 
  CDL.ContentDocumentId = CN.Id;
  CDL.LinkedEntityId ===CN.<field which has TaskID> 


  If(CDLInsert.size() > 0){
     try {
    insert CDLInsert;
     } else {


Just follow along the lines that you inserted records before. You are now taking the list you built and creating DocumentLints. Hope this helps !!!
Parvinder ChanaParvinder Chana
Hi Deepak, Appreciate the quick reply but there is no field in contentnote with has taskid. I need to get task id from task object which will be task.id. Thanks
Parvinder ChanaParvinder Chana
May be we have to do this, 

for each new task
    get task id
    insert into content note
   get content note after record is inserted

   insert task id and content note id into contentdocumentlink 

not sure if we can loop thru each new task record and then add record in content note and contentdocumentlink