+ Start a Discussion
Arjun SrivastavaArjun Srivastava 

Setting Visibility field on ContentDocumentlink in APEX

Hello,

I am referring to this salesforce knowledge article (https://help.salesforce.com/articleView?id=000320738&language=en_US&type=1&mode=1) which says that ContentDocumentLink.Visibility can be set in the Apex.

We need to set visibility to "All Users" for the ContentDocumentLink in the apex but we are not able to set contentDocumentLink visibility as "AllUsers" for SObject in the apex.

I am receiving the error which is working in any new dev org but not in the sandbox. Please advise if any setting we need to enable. 
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( before insert,after insert)
{
   if(Trigger.isBefore || Trigger.isInsert)
   {
       for(ContentDocumentLink cont : Trigger.new)
       {
           cont.Visibility = 'AllUsers'; // getting error here
           cont.ShareType = 'I';
       }
   }
}

Getting error at "cont.Visibility = 'AllUsers';" saying :Record is read-only".​​​​ We have tried setting it at after insert also but the same error.

Error: There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger ContentDocumentLinkTrigger caused an unexpected exception, contact your administrator: ContentDocumentLinkTrigger: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.ContentDocumentLinkTrigger: line 7, column 1"

Note: ContentDistrribution is already enabled in the org.
Best Answer chosen by Arjun Srivastava
Coding-With-The-ForceCoding-With-The-Force
It's your logic that is causing the problem. It's allowing the code to run on after insert. You can't update a record in the after portion of the trigger. Change your code to this and it should work.
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( before insert,after insert)
{
   if(Trigger.isBefore)
   {
       for(ContentDocumentLink cont : Trigger.new)
       {
           cont.Visibility = 'AllUsers'; // getting error here
           cont.ShareType = 'I';
       }
   }
}

by removing the "|| trigger.isinsert" check you will fix your problem.

-Matt