2

I've got a custom JS button on a custom object call Card, and the Card object is child to Contract (via Lookup). That JS button (called New Adult Card) shows up on the Cards related list on the Contract page layout (i.e. I have access to Contract merge fields in the button. So when I do {!Contract.Account}, that let's me reference the standard Account lookup on the Contract object. All out of the box, that works fine... except what if that Account has a special character in it? JSENCODE to the rescue, right?

Wrong, {!JSENCODE(Contract.Account)} returns the Id of the Account record. Huh?

JSINHTMLENCODE() and URLENCODE() both work in exactly the same way.

{!JSENCODE(Contract.Account.Name)} doesn't even save, throws an invalid field error.

I worked around it with the following, which is fine, but I'd like to understand the observed behavior mentioned above. Anyone have any bright ideas?

var acctName = "{!Contract.Account}";<br/>
alert(acctName);<br/>
var acctNameEncode = encodeURIComponent(acctName);<br/>
alert (acctNameEncode);
1

If you're using a Master-Detail relationship, the following button code is valid:

alert("{!JSENCODE(Account.Name)}")

If you're not using a Master-Detail relationship, you have to use some other method of getting the account name; your "solution" works so long as there are no embedded character returns or matching quotes (in your case, double-quotes), which would form illegal JavaScript syntax. Obviously, Account Name won't contain an embedded return line, but other types of fields could, such as formulas or text areas.

You must still be wary of quotes appearing in the text field. A better solution would be to use the REST API or SOAP API (e.g. using the AJAX Toolkit) to retrieve the account name. This method would only use API calls when the user the clicks on the button. For example:

{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
sforce.connection.query(
    "select account.name from contract where id = '{!Call__c.ContractId__c}'", 
    { onSuccess: 
          function(data) { alert(data.records[0].Account.Name); }, 
      onFailure: 
          function(error) { alert(error.message) 
    }
);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.