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 

Problems with blocking document types with triggers and Metadata

Hello,
I tried to block XLS;XLSX, PPT and PPTX to be be uploaded in my sandbox. I already build 4 records in the "DataBlock" object with the 4 types:
User-added image With this metadata I build 2 triggers but I still cant block only these types. Can you tell me where I have to change my code?


trigger DataBlock on ContentDocument (before insert) {
try {   
    Set<String> blockedTypes = new Set<String>();
    for (DataBlock__mdt  blockedType : [SELECT FileExtension__c FROM DataBlock__mdt WHERE FileExtension__c != null]) {
        blockedTypes.add(blockedType?.FileExtension__c?.toUpperCase());
    }
    for (ContentDocument myDocument : Trigger.new) {
        if (myDocument.FileExtension != null && blockedTypes.contains(myDocument?.FileExtension?.toUpperCase())) {
            myDocument.addError('The file extension ' + myDocument.FileExtension + ' is not allowed.');
        }
    }
} catch (Exception e) {
    throw new StringException(e.getMessage() + ' - ' + e.getLineNumber() + '\r\n' + e.getStackTraceString());
}

}

And the second trigger:

trigger DataBlockContentVersion on ContentVersion(before insert) {
    try {   
        Set<String> blockedTypes = new Set<String>();
        for (DataBlock__mdt  blockedType : [SELECT FileExtension__c FROM DataBlock__mdt WHERE FileExtension__c != null]) {
            blockedTypes.add(blockedType?.FileExtension__c?.toUpperCase());
        }
        for (ContentVersion myDocument : Trigger.new) {
            if (myDocument.PathOnClient != null) {
                String[] parts = myDocument.PathOnClient.split('.');
                if (parts.size() > 0) {
                    String ext = parts[parts.size() - 1];
                    if (blockedTypes.contains(ext.toUpperCase())) {
                        myDocument.addError('The file extension ' + myDocument.FileExtension + ' is not allowed.');
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new StringException(e.getMessage() + ' - ' + e.getLineNumber() + '\r\n' + e.getStackTraceString());
    }
}
Vishwajeet kumarVishwajeet kumar
Hello,
Trigger on ContentVersion should work, if you are trying to restrict it for "Files" (not Attachments Or Documents). Try to compare "FileExtension" field of ContentVersion.

Thanks