[SalesForce] Retrieving an image from rich text field

Have a rich text field called – snapshot__c which has image in it. This field is inside custom object called obj__c.

obj__c has another field case__c using lookup in it.

On a Vf page, I'm selecting a case and need to display the image (snapshot__c). I am able to fire the query, but the image isn't just getting displayed. Instead getting something weird. Image for reference:

enter image description here

Query in controller:

con = [select snapshot__c from obj__c WHERE Case__c =: ex.case__c];

VF pageblock:

<apex:pageBlockTable value="{!con}" style="width:1200px;" var="c" rendered="{!if(showPB==true,true,false)}" border="2" title="Some Name">
    <apex:column value="{!c.snapshot__c}" style="width:500px;" rendered="false" />
</apex:pageBlockTable>

Any alternative for apex:pageBlockTable and/or apex:column ? Can I just use div and how? What am I doing wrong? Pls help.

Best Answer

Rich fields are stored as HTML in Salesforce, so to retrieve your image, you will have to parse the text and get the image from there. Luckily this is a fairly simple task to do.

Once queried, the field will look like this in the variable:

enter image description here

What you want is what is in the src attribute of the img tag. You can just copy the tag, or get the link and remake it in your page (using a repeat attribute or something).

Here's a sample code on how you would do this (I used a Developer Edition organization with a object from Trailhead):

Campsite__c camp = [SELECT Id, RichField__c FROM Campsite__c LIMIT 1];

System.debug('Rich field:');
System.debug(camp.RichField__c);

String firstSubString = camp.RichField__c.substringBetween('<img', 'img>');
System.debug('First substring: ' + firstSubString);

String secondSubString = firstSubString.substringBetween('src="', '"');
System.debug('Second substring: ' + secondSubString);

String link = secondSubString.replace('amp;', '');
System.debug('Link: ' + link);
Related Topic