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 

Change trigger to only look on the latest version to determine if File can be deleted

Hello, I have a problem with a trigger that I have. I created a field in Content Version named "Dokumentenklasse" and if a file with the value i.e Vertragsdokument  is chosen, the trigger should lead to it, that this file can not be deleted. Everything to this point is working absolutely fine.

The problem is that when I create a new version on a document that cant be deleted and give it a Dokumentenklasse that could be deleted, I still get the error, because the old version blocks the deletation.
Could you show me how to change the trigger code, that only the last version is looked at, when I try to delete the file instead of every possible version?

Thank you for the help!

My code:

trigger DokumentenklasseDelete on ContentDocument (before delete) {       
    map<id,ContentDocument> documentMap = new map<id,ContentDocument>([SELECT id,(SELECT Id,FileType,Dokumentenklasse__c from ContentVersions) from ContentDocument where id IN :trigger.old]);         
    for(ContentDocument con : Trigger.old){              
        List<ContentVersion> versionList = documentMap.get(con.Id).ContentVersions;         
        if (versionList != null && versionList.size() > 0) {        
            for (contentVersion cv : versionList) {  
                set<STring> setValues = new set<STring>{'Geschäftsbrief', 'Vertragsdokument', 'Wichtige Dokumentation oder Entscheidung', 'Druckstück'};
                if(setValues.contains(cv.Dokumentenklasse__c)) { con.adderror('Fehler: Dokumente der Dokumentenklassen "Geschäftsbrief", "Vertragsdokument", "Wichtige Dokumentation oder Entscheidung", sowie "Druckstück" dürfen aus rechtlichen Gründen vor Ablauf der Aufbewahrungsfrist nicht gelöscht werden. Kontaktieren Sie hierfür bitte einen Systemadministrator.');
                }              
            }            
        }                    
        
    } 
}