1


I'm trying to show the users an error when they are uploading files with unsafe extentions. here is the code:

trigger MNR_AttachmentTrigger on Attachment (before insert)
{

    List<BMCServiceDesk__Incident__c> co = [select id, Attachment_Added__c from BMCServiceDesk__Incident__c where id =: Trigger.New[0].ParentId];          

    If(co.size()>0)          
    {              
        co[0].Attachment_Added__c = True;              
        update co;          
    } 

    for(Attachment att:trigger.new)
    {
        String aName = att.Name;
        String aBody = EncodingUtil.Base64Encode(att.Body);
        String aType = att.ContentType;
        String aParentIncidentID = null;

        if(Schema.BMCServiceDesk__Incident__c.SObjectType == att.ParentID.getSobjectType())
        {
            aParentIncidentID = att.ParentId;
        }

        Set<String> allowed_images = new Set<String>{'png', 'jpg', 'gif', 'tif', 'tiff', 'jpeg'};
        Set<String> allowed_docs = new Set<String>{'xls', 'xlsx', 'csv', 'xml', 'txt', 'html', 'htm', 'pdf', 'doc', 'docx', 'rtf'};
        Set<String> allowed_multi_media = new Set<String>{'ppt', 'pptx', 'mp4', 'avi', 'mpg', 'mpeg', 'vob', 'mov', 'wmv'};
        String att_extention = aName.substring(aName.lastIndexOf('.') + 1);

        if(!allowed_images.contains(att_extention) && !allowed_docs.contains(att_extention) && !allowed_multi_media.contains(att_extention))
        {
            att.addError('Files of type \'' + aName.substring(aName.lastIndexOf('.')) + '\' are not allowed.');
        }
        else
        {
            Attachment_Callout.CreateCallout(aName, aBody, aType, aParentIncidentID);
        }
    }
}

However, I don't see any error massage other then in the logs.

8
  • Could you please provide your whole code? Are you using this in a trigger? Commented Feb 2, 2017 at 14:09
  • Hi Martin, I've updated post.
    – Lior Lavi
    Commented Feb 2, 2017 at 14:22
  • Are you sure you reach the condition of the addError? I don't see any erros in your code. How do you insert this attachments? Commented Feb 2, 2017 at 14:25
  • I'm using an application called BMC Remedyforce which have an Incident object that can have an attachment object added to it. When I add a file with a bad extention the error appear in the logs, but not on screen.
    – Lior Lavi
    Commented Feb 2, 2017 at 14:36
  • Here's what I found on the documentation: "When used on Trigger.new in before insert, the error message is displayed in the application interface.When used in Visualforce controllers, the generated message is added to the collection of errors for the page." Commented Feb 2, 2017 at 14:38

0

You must log in to answer this question.

Browse other questions tagged .