7

我有一个名为 Current_Address__c 的自定义字段,其数据类型为 textarea。

我需要按以下格式填充此字段。即街道后的换行符和zip后的另一个换行符。

街道 城市 国家 邮编 国家

城市国家邮政编码国家等的值取自联系对象。我不想将其用作公式字段。所以我需要在我的控制器中填充它并在我的 VF 页面上显示它。

我正在尝试使用下面的代码添加换行符

this.customobj.Current_Address__c = currentStreet + '\\n ' + currentCity + ' ' + currentState  + ' ' + currentZIP  + '\\n ' + currentCountry ;

我也使用了 \n 而不是 \n。

它仍然以一行而不是 3 行显示该字段

编辑

我使用以下代码完成了这项工作。我会接受 mathews 的答案,因为它可以与 outputfield 一起使用。

                currentAddress = currentStreet;
            currentAddress += '\r\n';
            currentAddress += currentCity + + ' ' + currentState  + ' ' + currentZIP ;
            currentAddress += '\r\n';
            currentAddress += currentCountry;

这仅在您使用 += 时有效。不知道为什么会这样

4

4 回答 4

8

我想我找到了问题,你有两个转义字符斜杠(\\n),但只需要一个,因为\n在这种情况下不需要转义斜杠。

此外,Salesforce 将新行另存为\r\n. 试试这个:

this.customobj.Current_Address__c 
    = currentStreet + ' \r\n' 
    + currentCity + ' ' + currentState  + ' ' + currentZIP  + ' \r\n' 
    + currentCountry;

此方法在使用<apex:outputfield>带有 sObject 字段的 an 时有效。

<apex:outputtext value="{!myCustomSObject__c.Address__c}"/>

如果您使用不同的 Visualforce 组件,它将不起作用。使用<apex:outputtext>组件时,Visualforce 会在 HTML 中呈现新行,但 HTML 会忽略新行。如果您使用<br/>标签,Visualforce 会将其呈现为&lt;br/&gt;.

对于呈现包含新行的变量(而不是 sObject 字段),我能想出的最佳解决方案是使用 disabled <apex:inputtextarea>.

<apex:inputtextarea value="{!myAddress}" disabled="true" readonly="true">
</apex:inputtextarea>
于 2012-04-10T14:01:04.293 回答
3

最近我遇到了同样的问题,我想在我找到的解决方案中重新添加新行,这有点棘手,但它有效:

<apex:outputText value="{!SUBSTITUTE(JSENCODE(textVariableThanContainsNewLines), '\\n', '<br/>')}" escape="false"/>
于 2013-08-21T15:09:15.503 回答
0

试试这个:

控制器

public List<String> getLetterLines() {
    if (letterBody == null) {
        return new List<String>();
    }
    return letterBody.split('\n');
}

VF 页面:

<apex:repeat value="{!letterLines}" var="letterLine">
    <apex:outputText value="{!letterLine}" /><br />
</apex:repeat>

玩得开心!

于 2014-08-19T09:07:10.477 回答
-3

value="备注: {!SUBSTITUTE(JSENCODE(textVariableThanContainsNewLines), '\r\n', '
')}"

于 2015-01-21T21:50:34.057 回答