So there are two use case :
1. Upload new file
2. Relink existing file
Lets consider below use case.
I want to restrict user from uploading file in Contact record if the Level__c is ‘Primary’
So lets understand file ,
In Salesforce, ContentDocumentLink is an object that represents the link between a ContentDocument and a Salesforce record. It essentially associates a Salesforce record with a document in Salesforce CRM Content or a file in Salesforce Files. This link allows users who have access to the record to access the document. It also determines how the document is shared and with whom.
The ContentDocument represents a document that has been uploaded to a library in Salesforce CRM Content or to a file in Salesforce Files. It includes information about the document, such as its title, type, and other properties.
The ContentDocumentLink object is used to share documents with users, groups, records, and Salesforce CRM Content libraries. It also determines the visibility of the document to other users in the organization.
By linking the ContentDocument to records through ContentDocumentLink, users can easily access and share documents related to specific records within Salesforce.
When a user uploads a new version of a document, a new record is created in the ContentVersion object, and the version history of the document is maintained. Each version of the document is associated with a ContentDocument record that represents the document.
ContentVersion is closely related to ContentDocument, as each ContentVersion record is linked to a single ContentDocument. The ContentDocument serves as the parent record for one or more related ContentVersion records representing different versions of the same document.
Users can view the details of each version, download specific versions, and track the version history of the document. ContentVersion allows for the efficient management of document versions and facilitates collaboration and sharing within the Salesforce platform.
So, we need to write Trigger on ContentDOcumentLink and compare the Parent record field using LinkedEntityId field.
PFB the sample code:
trigger ContentDocumentLinkTrigger on ContentDocumentLink (before insert) {
set<Id> parentIds = new set<Id>();
map<Id, Contact> contactMap;
//get the parent ids
for (ContentDocumentLink content : Trigger.new) {
if(content.LinkedEntityId!=null){
parentIds.add(content.LinkedEntityId);
}
}
//now build the parent record map and check the Level value
if(!parentIds.isEmpty()){
getContactDetails(parentIds);
for (ContentDocumentLink content : Trigger.new) {
if(contactMap.get(content.LinkedEntityId).Level__c == 'Primary'){
content.addError('You can not upload file.');
}
}
}
//Method return map of parent record
public static void getContactDetails (set<Id> conSet){
contactMap = new map<Id, Contact>( [select Id,Level__c
from Contact
where Id IN: conSet]);
}
}

