function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Temple SutfinTemple Sutfin 

Stringbuilder equivalent?

I am writing a chunk of code to take information from a custom object, and place it into an email when a partner portal user selects a custom button.

 

When it comes to building the body of the email, I am trying to find a way to make it look nice.

In .NET I could use stringbuilder to assemble the line breaks and feed in the variables where needed then convert to a string.

 

Is there an equivalent to that in Salesforce? 

Does anyone have an example of syntax for it?

 

Thanks,

Temple Sutfin

Best Answer chosen by Admin (Salesforce Developers) 
Temple SutfinTemple Sutfin

Well ... here is a way to add line breaks and tabs ...

It took me quite some time to find this through google, which was frustrating, but I was able to at least clean up the email template to look presentable.

In my body variable, I used a stringbuilder mentality to append lines, but used '\t' for tabs and '\n' for new line.

 

So:

 

body = 'Hello ' + owner.Name + ',\n';

body += '\t I am writing ...';

 

While this approach was brutal to build, it did work.  I would prefer a better solution to mine, but sometimes finding reference material with Google, Developer.force, stack overflow, etc is like trying to find ... *insert simile cliche here* ...

 

 

All Answers

Tanvir AnsariTanvir Ansari

Are you doing an HTML email? If yes then the use <html> tags to beautify your email. It also meant using APEX emails

Jake GmerekJake Gmerek
Or you could build out a VF email. That would give you a ton of options.
Temple SutfinTemple Sutfin

I am using Apex and Visualforce.

 

I am not using Email Templates.

 

VF:

<apex:page controller="RenewalQuoteEmail" tabStyle="Contract_Owner__c" sidebar="False" showHeader="False"> 
<apex:messages />
    <apex:form >
        <apex:pageBlock title="Forward Lead to Email Recipient." Mode="Edit">
        <apex:pageBlockSection title="Email Message" columns="1">
        
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="To" for="email"/>
            <apex:outputPanel styleClass="requiredInput" layout="block">
            <apex:outputPanel styleClass="requiredBlock" layout="block"/>
                <apex:inputText value="{!emailTo}" id="email" required="True"/>
            </apex:outputPanel>
        </apex:pageBlockSectionItem>
        
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="Cc" for="emailCc"/>
            <apex:inputText value="{!emailCc}" id="emailCc" />
        </apex:pageBlockSectionItem>            
        
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="Subject" for="Subject"/>
            <apex:outputPanel styleClass="requiredInput" layout="block">
            <apex:outputPanel styleClass="requiredBlock" layout="block"/>
                <apex:inputTextArea cols="80" rows="1" value="{!subject}" id="Subject" required="True"/>
            </apex:outputPanel>
        </apex:pageBlockSectionItem>            
        
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="" for="Body"/>
            <apex:inputTextArea cols="80" rows="10" value="{!body}" id="Body" />
        </apex:pageBlockSectionItem>
    
    </apex:pageBlockSection>
    <apex:pageBlockButtons location="Bottom">
            <apex:commandButton value="Send Email" action="{!sendEmail}" onclick="{top.close()}"/> 
            <apex:commandButton value="Cancel" action="{!cancel}" onclick="{top.close()}" /> 
    </apex:pageblockbuttons>
    </apex:pageBlock>
    </apex:form>
</apex:page>

 and Class:

     public RenewalQuoteEmail() {
       owner = [SELECT id, Vendor_1_Email__c, Renewal_Name__c, Vendor_1_Contact__c FROM Renewal_Year__c WHERE id = :ApexPages.currentPage().getParameters().get('id')];
       subject = 'Renewal Quote Request for ' + owner.Renewal_Name__c;
       body = 'Hello ' + owner.Vendor_1_Contact__c + ', I am working on the **Renewal** at the **Company Name**  Please send me a detailed quote that lists all the products and the Terms for the renewal.';
       emailTo = owner.Vendor_1_Email__c;
          }

 What I need to do is display a lot of data in the body of the email that depends on Child records, and needs to have conditions on the email generation depending on certain fields being filled out in the parent custom object.

 

I would like to accomplish this without using an Email Template.  But I am not sure how to go about assembling the body language to prevent one giant concatonated run on string.

 

Thoughts?

Tanvir AnsariTanvir Ansari
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); body ='<html><style type="text/css">body {font-family: Arial; font-size: 12px;}</style><body><pre>'; body += 'Hi,'; body +='<br/><br/>A potential duplicate record for '+myobject.firstname+' '+myobject.lastname+' has been created' ; //by '+mapuser.get(myobject.Ownerid)+'.' ; body +='<br/><br/>This is currently owned by '+myoldvalue.owner.FirstName+' '+myoldvalue.owner.LastName+' with the earliest Realtor Contact creation date of: '+ myoldvalue.CreatedDate +'.'; body +='<br/><br/>Please take the necessary action.'; body +='<br/><br/><b>Current Details: </b>'; body +='<br/>Name: '+myoldvalue.firstname+' '+myoldvalue.lastname; if(myoldvalue.phone!=null) body +='<br/>Phone: '+myoldvalue.phone; if(myoldvalue.email!=null) body +='<br/>Email: '+myoldvalue.email; if(myoldvalue.homephone!=null) body +='<br/>Home Phone: '+myoldvalue.homephone; if(myoldvalue.mobilephone!=null) body +='<br/>Mobile: '+myoldvalue.mobilephone; body +='<br/><br/><b>New Contact Details: </b>'; body +='<br/>Name: '+myobject.firstname+' '+myobject.lastname; if(myobject.phone!=null) body +='<br/>Phone: '+myobject.phone; if(myobject.email!=null) body +='<br/>Email: '+myobject.email; if(myobject.homephone!=null) body +='<br/>Home Phone: '+myobject.homephone; if(myobject.mobilephone!=null) body +='<br/>Mobile: '+myobject.mobilephone; body +='<br/><br/>Regards,<br/>Salesforce Admin'; body +='</pre></body></html>'; email.setSubject( subject ); useremaillist.add('Tanvir.Wipro@gmail.com'); email.setToAddresses(UseremailList); email.sethtmlbody( body ); Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); }catch(Exception e){ system.debug(' $ Exception in sending Mail $$ '); }
Jake GmerekJake Gmerek

So you will have to build the string in your controller I would think unless you could use a pageblocktable or a data table.  Not sure how your data will look in the end, but you could possible use multiple strings.  If you add HTML tags use apex:outputText tags and escape=false (I think, maybe true you'll have to play with it) to get the tags to be rendered properly.  I'll use something like this to build long strings:

 

string myString = 'first part';

myString = myString + 'second part';

 

and so on.  Sorry that I can not get more specific, but I am not sure what you want to the data to look like and there are several options that would be chosen based on what you are trying to do.  If you have specific questions let me know and I would be happy to answer them.

Temple SutfinTemple Sutfin

Well ... here is a way to add line breaks and tabs ...

It took me quite some time to find this through google, which was frustrating, but I was able to at least clean up the email template to look presentable.

In my body variable, I used a stringbuilder mentality to append lines, but used '\t' for tabs and '\n' for new line.

 

So:

 

body = 'Hello ' + owner.Name + ',\n';

body += '\t I am writing ...';

 

While this approach was brutal to build, it did work.  I would prefer a better solution to mine, but sometimes finding reference material with Google, Developer.force, stack overflow, etc is like trying to find ... *insert simile cliche here* ...

 

 

This was selected as the best answer
Tanvir AnsariTanvir Ansari
But this will only give you text wityh newline character. I provided you solution which is similiar with an HTML tags. I am not sure if there can be any better solution as the requirement itself is to build a string and format it and it will be tedious.
Temple SutfinTemple Sutfin

When I used the html tags, they came through rendered as <html> <body> <br /> <p> etc. in my output instead of linebreaks, paragraphs, etc.. 

 

I am sure there is a way to escape that, but when I found the \t and \n I stopped looking for ways to do it the html way and just went for the newlines and tabs.

 

I like your approach better Tanvir, as I know that with HTML and CSS I can create a kick-butt template, but I stopped looking out of sheer frustration.  I would rather use HTML because I am more comfortable with it, but I fall short of having a solution that works when I try to use it.  This is a button click, calling apex code that renders on a visualforce page the user can edit before sending the email. 

 

 

 

Jake GmerekJake Gmerek
For future reference from my post above:

"If you add HTML tags use apex:outputText tags and escape=false (I think, maybe true you'll have to play with it)"
Tanvir AnsariTanvir Ansari
I did get same issue an year back and did this, the solution is working till date and have implemented for 2 other client.

You must have missed out on may be some quotes and hence the result must be the output that you got. Also did you do this statement

email.sethtmlbody( body );

or not?
Tanvir AnsariTanvir Ansari
If the user can edit , did you build custom container for HTML edits or you are doing plain text?

I did same, where I build the string with controller, displayed it in text atea, allowed edit and on final submission email was build and sent. And yest escape=false statement will be needed. Although at present there are some limitations and not correct implementation exist that is what I found out
Temple SutfinTemple Sutfin

You have me a little confused here.

 

If I am using:

        <apex:pageBlockSectionItem >
            <apex:inputTextArea cols="80" rows="10" value="{!body}" id="Body" />
        </apex:pageBlockSectionItem>

to define the body that is being passed information from my apex class, how do I define the Apex:OutputText tag to reference the same body?

 

Am I replacing the inputTextArea tag with the OutputText tag?  If I do that, will I no longer have the ability to add text to the email block before hitting the final send?  ( I pasted the VF page code in a post earlier, and here is the logic for the Apex Class: 

public RenewalQuoteEmail() {
       owner = [SELECT id, Vendor_1_Email__c, Renewal_Name__c, Vendor_1_Contact__c 
                  FROM Renewal_Year__c 
                 WHERE id = :ApexPages.currentPage().getParameters().get('id')
                ];
       account = [SELECT Name FROM Account    etc. etc.
       subject = 'Renewal Quote Request for ' + owner.Renewal_Name__c;       
       body = 'Hello ' + owner.Vendor_1_Contact__c + ',\n';
       body += 'I am working on the Maintenance Renewals at the ' + account.Name + '\n';
       body += 'Please send me a detailed quote that lists all the products and the Terms for the renewal.';
       body += '\n\n\tCost Center\tProduct Name\t\tPrevious QTY\tNew QTY\tLast Cost\n';
       body += etc. etc.         
       emailTo = owner.Vendor_1_Email__c;
     }

 (for the sake of brevity, i pulled out extra stuff).

 

Please show me where I would use the outputText and I will play around with it to see if I can get it to work better.

Thanks.

Tanvir AnsariTanvir Ansari
Did you put richtext="true" attribute on the <apex:textarea for subject and body?
Tanvir AnsariTanvir Ansari

For me it was 2 step process where we allowed edit HTML and then showed the preview of email going out to the recipient for that used output text

Kimball RobinsonKimball Robinson
Perhaps you could add all the strings to a List<String> and then use String.join(...) like this:
List<String> l = new List<String>();
l.add('hello');
l.add(' ');
l.add('world');
String finalStr = String.join(l, '');