[SalesForce] Return a list of attachments for a custom object

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


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.

Best Answer

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):


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.

Related Topic