[SalesForce] Cannot update contentDocumentId in contentDocumentLink

I am sharing a file with a task by creating ContentDocumentLink.

The LinkedEntityId points to the task record.

Now, if a certain update happens to a parent record then i am trying to update only ContentDocumentId in the ContentDocumentLink that was previously inserted.

However, i am getting an exception,

execution of BeforeUpdate caused by: System.SObjectException: Field is
not writeable: ContentDocumentLink.ContentDocumentId

Do I need to delete previous ContentDocumentLink and insert a new ContentDocumentLink with updated ContentDocumentId?

Can't we update ContentDocumentId in ContentDocumentLink directly?

Best Answer

ContentDocumentId is of type reference and Properties are Create, Filter, Group, Sort. It is ID of the document which have been linked with any record.

Note:- Once you create a ContentDocumentLink, You can not update it.

If you are trying to change ContentDocumentId means you want to remove the current document shared with it and replace it with another document.

You must create another ContentDocumentLink with ContentDocumentId having your desired new document and LinkentityId with the record id of the record with which you want to share.

Side Note:- Inserting a new document needs to insert using ContentVersion Object as you cannot insert ContentDocument.

So, Your answer would be:-

  1. Yes, you need to delete the previous ContentDocumentLink and insert a new ContentDocumentLink with updated ContentDocumentId
  2. No, You can not update ContentDocumentId in ContentDocumentLink directly

Reference:-