+ Start a Discussion
Lindsey PalmquistLindsey Palmquist 

link notes from accounts to opportunities

I would like to be able to see notes that were created in Accounts in the same notes field when in opportunities and vice versa.  If someone enters information into the opportunities section, I would like it to populate into the notes section in accounts; same with accounts to opportunities.  Can someone please explain how to do this? Thank you! 
Asif Ali MAsif Ali M
Note is a very tricky object on Salesforce (Note Schema (https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_erd_contentnote.htm)) . Notes sharing is controlled through an Object called ContentDocumentLink (https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocumentlink.htm).  Here is the logic you need to implement
  • Create a After Insert trigger on ContentDocumentTrigger
  • Get the existing ContentDocumentLinks for a note:  When a note is created , Salesforce will insert 2 records in ContentDocumentLink. One is for the SharedObject and the other for the Owner. For example: If you add a note to Account then the sharing is given to Account and the user. 
  • Check the SharedObject type. Use the value of ContentDocumentLink.LinkedEntityId to findout the Object Type. If it is Account get the related Opportunities , if it is Opportunity then get the Related Account Id.
  • Now share the Note with the related records by inserting records into ContentDocumentLink
Find the psuedo code to get an Idea 
// cdl is instance of ContentDocumentLink
Id recordId = cdl.LinkedEntityId;

sobject[] needToShare;

String objectType = recordId.getSObjectType().getDescribe().getName();

if (objectType == 'Account') {
    needToShare = [select Id from Opportunity where AccountId = :recordId];

if (objectType == 'Opportunity') {

    needToShare = [select Id, AccountId from Opportunity where Id = :recordId];

system.debug( needToShare);

List <ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
for (SObject currentObject: needToShare) {
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = noteId; // NOTE ID
    cdl.LinkedEntityId = (objectType=='Account') ?currentObject.Id :AccountId.AccountId;
    cdl.ShareType = 'C'; // Change the value as per your need

insert cdl;