function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonathan Wolff 7Jonathan Wolff 7 

Trigger to prevent file delete with picklist value

Hello ,

I have a field on Content Version called Dokumentenklasse__c that has the type picklist. It is a required field for file upload
Can someone help me to write a trigger to prevent deletation of all files with the picklist value "Geschäftsbrief" in the dokument object field.
No user should be able to delete this files

I appreciate every kind of help.
Greetings
Jonathan
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution. 

trigger ContentVersionTrigger on ContentVersion (before delete) {
   
    set<Id> contentId = new set<Id>();
     if(trigger.IsDelete){
	 
        for(ContentVersion con : Trigger.old){
            contentId.add(con.Id);
        }
		 List<Attachment> at=[select name,body,contentType from Attachment where parentid in: contentId];
		 
		 
          for(ContentVersion con : Trigger.old){
            if(con.Dokumentenklasse__c =='Geschäftsbrief'){
			if(at.size()>0){
			con.addError('You cant delete the file');
			}
			}
        }
    }
}

Do some Needful Changes according to your code.

Please mark it as the Best answer if it helps you.

Thank You

Jonathan Wolff 7Jonathan Wolff 7
Hi Suraj, sadly it did not work. I was still able to delete the file with the "Geschäftsbrief" value :(
Could it be that it is not List<Attachments> ? or some fault like that
Suraj Tripathi 47Suraj Tripathi 47

try this

trigger ContentVersionTrigger on ContentVersion (before delete) {
 

    Set<Id> contentDocumentIdSet = new Set<Id>();
 if(trigger.IsDelete){
 
 
 
	for(ContentVersion con : Trigger.old){
		 if(con.ContentDocumentId != null)
        {
            contentDocumentIdSet.add(con.ContentDocumentId);
        }
	}
	
	ContentDocumentLink cdl = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet Limit 1];
	


 	 
	 
	  for(ContentVersion con : Trigger.old){
		if(con.Dokumentenklasse__c =='Geschäftsbrief'){
		if(cdl!=null){
		con.addError('You cant delete the file');
		}
		
		}
	}
	
	
}


}

Please let me know it is working or not?

Thanks