0

I would like to display the the first image attachment for a record in my visualforce page.

The visualforce page uses a standard controller to get the record data and I've built an extension to retrieve the attachments.

APEX Extension:

public with sharing class NewsController {

    private final News__c newsArticle;
    public list<News__c> con {get;set;}

    public NewsController(ApexPages.StandardController controller) {
        this.newsArticle = (News__c)controller.getRecord();

    }

    public List<News__c> getPostAttachments() {
        String newsId = Apexpages.currentPage().getParameters().get('id');
        con = new List<News__c>();
        con = [SELECT Id, (Select Id, Name, LastModifiedDate From Attachments Order By LastModifiedDate DESC) FROM News__c WHERE Id = :newsId];
        return con;
    }
...

Visualforce Page:

<apex:page title="{!News__c.Title__c}" standardController="News__c" extensions="NewsController">
...
<apex:image url="{!URLFOR($Action.Attachment.Download, PostAttachments.Attachments[0].Id)}" rendered="{!PostAttachments.Attachments.Size>0}"></apex:image>

When saving the VF page I get an error stating

(NewsPage) Unknown property 'VisualforceArrayList.Attachments'

Could someone tell me what I'm doing wrong here?

And secondly could someone help me filter this list out so only images are returned (jpg/gif/png) incase a user adds other attachments?

1

Your error is because PostAttachments is already a List, being rendered as a VisualforceArrayList. You're attempting to call PostAttachments.Attachments and then index that here:

PostAttachments.Attachments[0].Id)}" rendered="{!PostAttachments.Attachments.Size>0}">

It's being thrown because there is no property on PostAttachments called "Attachments." Without being familiar with the structure of your class News__c, I would guess that you should try to index PostAttachments itself and go from there.

  • Could you give me an example that I could use or maybe I can add more detail to the question for a better explanation? I'm finding it difficult to understand how I can flatten so there isnt a list within a list. – Deployment Failure Apr 1 '15 at 14:30
  • Does this help? help.salesforce.com/apex/… – Brian Mansfield Apr 1 '15 at 14:37
  • 1
    Just try replacing PostAttachments.Attachments[0].Id with PostAttachments[0].id in your URLFOR function and let us know how that goes – Brian Mansfield Apr 1 '15 at 14:39
  • Using PostAttachments[0].Attachments[0].Id has worked :D – Deployment Failure Apr 1 '15 at 14:53
  • For efficiency could you tell me more about trying to flatten the list? – Deployment Failure Apr 1 '15 at 14:54

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.