[SalesForce] How to avoid this JSENCODE() error when the help text is blank

I've written a VF page that uses a lot of JavaScript. One particular pattern is giving me some trouble. I'm pulling the help text into a JavaScript object array, like so:

var columns = [
        {
            id: "NAME",
            name: "{!$ObjectType.Custom_Object__c.fields.Name.Label}",
            field: "Name",
            tooltip: "{!JSENCODE($ObjectType.Custom_Object__c.fields.Name.inlineHelpText)}"
            width: 300,
            sortable: true
        },

There's one for every column. JSENCODE is absolutely crucial otherwise the help text will inject directly into the javascript, including any carriage returns

When the help text for the field is blank, however, I get the following error:

Invalid argument type for function 'JSENCODE()'

However, nothing else I've tried works. I've tried using ISNULL() to check for a null value before passing to JSENCODE() but I still get the error, as it seems to parse the JSENCODE() with the blank helpText even though the formula would prevent that. I've tried using BLANKVALUE() to pass a value conditionally to JSENCODE, but I get the error the BLANKVALUE() is expecting OBJECT and recieves TEXT. TEXT() also says that it is an invalid argument either way.

Basically it seems like a bug – JSENCODE() with helptext passed through should work just as well when the help text is blank, and, in fact, it does – if I save the VF page and then delete the help text from the field definition, the page renders fine. But the page won't save if I've passed help text to JSENCODE() that is blank in the field definition, and I can't find a workaround for it.

Best Answer

Visualforce recognizes InlineHelpText is null for Name at compile-time. Interesting!

Your quickest fix is to dynamically dereference the field: Fields['Name'] vs Fields.Name

var columns = [{
    id: "NAME",
    name: "{!JSENCODE($ObjectType.Custom_Object__c.Fields['Name'].Label)}",
    field: "Name",
    tooltip: "{!JSENCODE($ObjectType.Custom_Object__c.Fields['Name'].InlineHelpText)}"
    width: 300,
    sortable: true
}];

Also recommend the use of JavaScript bridging components to separate the VF and the JS.

Related Topic