aheber
6/11/2014 - 11:15 PM

Salesforce Email Friendly multi-line output used to prevent the javascript spew that outputField causes

Salesforce Email Friendly multi-line output used to prevent the javascript spew that outputField causes

/*component*/

<apex:component controller="OutputTextHTML" access="global">
  <apex:attribute name="value" description="Text to be HTML formatted" type="String" assignTo="{!myText}"/>
  <apex:outputText value="{!myHTMLSafeText}" escape="false"/>
</apex:component>


/*controller*/

public class OutputTextHTML {
    public String myText{get;set;}
    public String myHTMLSafeText{
        get{
            if(myText == null)
                return myText;
            
            String myCleanText = myText.escapeHtml4();
            myCleanText = myCleanText.replaceAll('(\r\n)|(\n\r)|\r|\n','<br />');
            return myCleanText;
        }
    }
}


/*test*/

@isTest
public class OutputTextHTMLTest{
    public static testMethod void stringOutput(){
       OutputTextHTML htmlEncoder = new OutputTextHTML();
       //Catch null clause
       String out = htmlEncoder.myHTMLSafeText;
       htmlEncoder.myText = 'this is <a> test';
       out = htmlEncoder.myHTMLSafeText;
       System.assertEquals(out,'this is &lt;a&gt; test');
       
       htmlEncoder.myText = 'this\nis\na\ntest';
       out = htmlEncoder.myHTMLSafeText;
       System.assertEquals(out,'this<br />is<br />a<br />test');
    }
}