2

I'm looking at the following example to upload some attachments to a custom object,

http://blog.jeffdouglas.com/2010/04/28/uploading-an-attachment-using-visualforce-and-a-custom-controller/

It works perfectly, but I'm now looking to reverse the process and return all these attachments and display them in a list or a table or anything.

I'm not really sure where to begin. I'm assuming I need to add anew method in the controller which will run when the page loads, but again I'm a little unsure how to approach this.

Any advice or suggestions would be greatly appreciated.

5

You can add a property to the controller that returns the collection of attachments using the "lazy load" pattern like this:

public Attachment[] attachments {
    get {
        if (attachments == null) {
            attachments = [
                    select Id, Name, Description, LastModifiedDate
                    from Attachment
                    where ParentId = :customObjectId
                    order by Name
                    ];
        }
        return attachments;
    }
    private set;
}

and use e.g. an apex:pageBlockTable to display the attachment fields as apex:columns.

If you want to have a "View" link in your table that opens the attachment in another tab/window, and don't mind relying on a URL that Salesforce may change in the future, this will work (assuming item is an Attachment):

<apex:outputLink
        styleClass="actionLink"
        target="_BLANK"
        value="/servlet/servlet.FileDownload?file={!item.Id}"
        >View</apex:outputLink>

Do not query the Body of the attachments as you cannot display that (in general) and you will run the risk of exceeding the allowed heap space in your controller.

3
  • I really appreciate the quick response Keith, very helpful!
    – Daft
    Apr 16 '14 at 8:18
  • In fact, I owe you a pint!
    – Daft
    Apr 16 '14 at 8:44
  • 1
    @Daft Finnegans it is then...
    – Keith C
    Apr 16 '14 at 8:50

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.