Escaping Quotes in Merge Fields

September 14, 2008 Appirio

Glenn Weinstein

S-controls, button on-click Javascript, and Visualforce pages can contain merge fields, which SFDC replaces with their record values prior to rendering. But this is a straight replacement, without any opportunity to escape characters. This leads to messy results when a merge field contains a double-quote character.

For example, consider using this merge field in on-click Javascript:

project.Name = “{!Opportunity.Name}”;

That would work great, but consider what happens if the opportunity is named Acme “World Peace” Project (with the double quotes). SFDC will render the code as:

project.Name = “Acme “World Peace” Project”;

Okay, now you have a huge mess. This will break the Javascript. A very clever workaround for this was created by an Appirio colleague of mine, Linda Evans. Here it is:

Step 1: Wrap the value in a hidden textarea.
Step 2: Retrieve the value by traversing the DOM.

So in our example above, first, you’d drop this HTML element into your page:

Then, inside a

project.Name = document.getElementById("opportunityName").value;

I told you this was clever - thanks Linda!

One final note, this won't work (directly) in a button on-click Javascript, since you can't put HTML elements in them (the entire body is considered a

Previous Article
Access Custom Fields on Standard Objects in Force.com IDE
Access Custom Fields on Standard Objects in Force.com IDE

Kyle Freeman I recently created a new Force.com Project in Eclipse, but was surprised to find that there wa...

Next Article
Defaulting your mailto: links to Google Apps in Firefox 3
Defaulting your mailto: links to Google Apps in Firefox 3

Tim Parker If you’re using Google Apps and Firefox and would like to default email links to open in Google ...