0

Please suggest if there is any way to restrict files without using trigger. If trigger is the only way then please review the below code and guide me to achieve this which is currently not working.

Trigger code for Chatter File restriction :

trigger FilterFileFormate on ContentVersion (after insert) {
    for (ContentVersion cv : Trigger.new) {
        // Origin is 'H' for Chatter files, 'C' for Content documents
        // Leave out the test for Origin if you want to cover both
        if (cv.Origin == 'H' && cv.FileType == 'EXE') {
            cv.addError('EXE files are not allowed to upload..!');
        }
    }
}

Modified the code as suggested : Code 2 :

trigger RestrictFilesOnFeedItems on FeedItem (after insert) {
    for(FeedItem fi : trigger.new){
        if(fi.type == 'ContentPost' && (fi.RelatedRecordId.FileType =='EXE' || fi.RelatedRecordId.FileType=='HTML' || fi.RelatedRecordId.FileType=='EDI')){

            fi.addError('Executable files, HTML & EDI file formats are not allowed to insert');
            }
}
}
1

Change your FeedItem trigger to AfterInsert.

type and many other fields don't get populated in the before trigger. So if you want to access the properties, after trigger is what you want.

If you want to check for the extension type of the file, use the RelatedRecordId field of FeedItem. The Id will be of ContentVersion which holds the fields such as fileExtension and fileType.

UPDATE:

Simply doing a fi.RelatedRecordId.FileType =='EXE' wont help because fi.RelatedRecordId is just an ID field, not a relation.

You will have to fetch all the RelatedRecordId for all record whose fi.type == 'ContentPost'.

Map<Id, FeedItem> contentversionIdToFeedItemMap = new Map<Id, FeedItem>();
for(FeedItem fi : trigger.new){
if(fi.type == 'ContentPost')
    contentversionIdToFeedItemMap.put(fi.RelatedRecordId, fi);
}

Now fire a query to fetch all the ContentVersion records with FieldType field and addError if it satisfies your condition.

for(ContentVersion cv : [SELECT Id, FileExtension,FileType FROM ContentVersion where Id IN :contentversionIdToFeedItemMap.keySet()])
{
    if(cv.FileType =='EXE' || cv.FileType=='HTML')
    {
        contentversionIdToFeedItemMap.get(cv.Id).addError('You can not add this type of file');
    }
}
2
  • Its not allowing me to proceed with fi.RelatedRecordId.FileType =='EXE', Please correct me to restrict it on filetype. Thanks – B1 sfdc Apr 13 '17 at 9:12
  • Updated my answer with explanation why it was not working and how it will work. – Santanu Halder Apr 13 '17 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.