views:

562

answers:

5

In Salesforce, if I'm binding a text field into a VisualForce page, whats a good way to convert the carriage returns in the text-field into HTML <br/> tags?

e.g. starting from something like this:

<apex:page standardController="Case">
  <apex:pageBlock title="Test">
      <p>{!case.Description}</p>
  </apex:pageBlock>                   
  <apex:detail relatedList="false" />
</apex:page>   

... if the Description is long with lots of carriage returns, how do I HTML-ify it?

(I guess this is a fairly easy question, and I'm sure I could google it, but to get the Salesforce community going on here I figure we need a few easy questions.)

edit: (Bounty added to try and generate some excitement)

A: 

Try this:

<apex:outputField value="{!case.Description}"/>

Using output fields will maintain formatting automagically.

TehNrd
This doesn't work for me. When I use outputField, carriage returns are not converted.
codeulike
A: 

Have you tried using outputText?

IF that does not work vote for my idea here: https://sites.secure.force.com/ideaexchange/ideaView?id=08730000000H4XDAA0 As I have the same issue when trying to return JSON to a page.

Other people also want this idea https://sites.secure.force.com/ideaexchange/apex/ideaview?id=08730000000BrhEAAS

Daveo
outputText and outputField did not work for me
codeulike
A: 

I eventually achieved this with some long winded code.

In the custom controller, add methods to return the field after manually searching and replace the line breaks in the field and replacing them with <br/> tags:

public string getCaseDescriptionFormatted()
{
    Case c = this.loadCaseFromDatabaseOrWhatever();
    return lineBreaks(c.Description);   
}

private string lineBreaks(string inText)
{
   if (inText == null)
       return '';
   else
       return inText.replaceAll('<','(').replaceAll('>',')').replaceAll('\n','<br/>');
}

Then in the page, use apex:outputText with escape="false":

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

Note that escape="false" is necessary to prevent VisualForce from escaping the html tags. This also means you leave yourself open to scripting-attacks that could by hypothetically embedded in the data. Thats why the lineBreaks() fn in the controller also replaces any < and > characters.

(There may be a better way to make the string safe, suggestions welcome)

codeulike
A: 

You could try something like:

{!substitute(Case.Description, '\n', '<br/>')}
ehartye
A: 

For me, TehNrd nailed it -- I was trying to display a Case "Description" in a VisualForce notification e-mail template, and all the CR/LFs disappeared and the lines / paragraphs were getting run together. Making it an OutputField value totally fixed it.

Laurent Stanevich

related questions