Skip to main content

I have a trigger and a apex class that should be showing a custom message when a user tries to upload a file on a record related list when the file name has too many characters. But when i test it, it shows the standard  Can't upload message. I'm not sure what I am doing wrong 

 

trigger tr_ContentVersionTrigger on ContentVersion (before insert) {

charContentVersionTriggerHandler.validateFileNameLength(Trigger.new);

}

public with sharing class charContentVersionTriggerHandler {

private static final Integer MAX_CHAR_LIMIT = 80;

public static void validateFileNameLength(List<ContentVersion> newFiles) {

for (ContentVersion file : newFiles) {

if (file.Title != null && file.Title.length() > MAX_CHAR_LIMIT) {

String errorMessage = 'The file name "' + file.Title +

'" exceeds the maximum system limit of ' + MAX_CHAR_LIMIT +

' characters. Please rename the file and try again.';

file.addError(errorMessage);

}

}

}

}

 

#Apex  #Triggers

1 answer
  1. Oct 23, 8:12 PM

    Your trigger is most likely firing fine. The catch is the Upload Files dialog on the related list doesn't show the text from addError on ContentVersion, it just replaces it with its own generic "Can't upload" message. You can confirm by turning on a debug log for your user and uploading a file with a long name, your message should show up in the log. 

    If blocking isn't a hard requirement, an easier route is to shorten the name in the same before insert instead of throwing an error, so the upload just goes through:

    if (file.Title != null && file.Title.length() > MAX_CHAR_LIMIT) { 

        file.Title = file.Title.left(MAX_CHAR_LIMIT); 

    } 

     

    Title doesn't include the extension (that's on PathOnClient / FileExtension), so the file still opens normally. If you do need to block it, it's probably worth adding a note near the related list so users know about the 80 character limit, since they won't see your custom text.

0/9000