A Tip A Day #36 – Display Image from Rich Text Field in VF Page

This post is a part of the daily blog series 

A Tip A Day, daily dosage of learning!


Day #36 – Display Image from Rich Text Field in Visualforce Page

I have a field of type Text Area (Rich)  called Product in a Contact object.  And I upload a picture to the field for one of the contacts.

rich-text-field-with-image-salesforce-sfdcfanboy.png

Solutions

Let’s look at what options do we have to display this field in a Visualforce page.

Option 1

If you are using a standard controller of contact, the solution is quite straightforward.  Use outputField and display the image.

<apex:outputField value="{!Contact.Product__c}"/>

Option 2

But most likely you’d be using a custom controller or an extension controller.   In that scenario, you’d be querying for the contact in your apex class.

So your text area field would be just be stored in a String variable called ‘ProdImage’.

String ProdImage = '';
List<Contact> conList = [SELECT Id,Product__c FROM Contact WHERE Id=:conId LIMIT 1];
if(conList!=null && conList.size()>0){
     ProdImage = conList[0].Product__c;
}

Of course, you cannot use outputField here because there is no standard controller here. So, we use outputText instead but using this gives just a “string” instead of an image.

<apex:outputText value="{!ProdImage}" />

So, to convert the string to the image format you just have to use an additional escape attribute.

<apex:outputText value="{!ProdImage}" escape="false"/>

 

 


Read all other tips of the blog series here – A Tip A Day, daily dosage of learning!


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

4 Replies to “A Tip A Day #36 – Display Image from Rich Text Field in VF Page”

Leave a comment