[SalesForce] How to render a checkbox with negated boolean value from model

I'm trying to render a readonly checkbox with a negated boolean value from my model.

Salesforce won't let you do this:

<apex:inputCheckbox disabled='true' value='{! !model.myBoolean}' />

i guess this is just meant for model binding

Or this:

<apex:inputCheckbox disabled="true" selected="{! !model.myBoolean}" />

So my next thought was fine, I'll just use a standard HTML input:

<input type="checkbox" disabled="true" {!if(model.myBoolean,'','checked')}" />

However, this apparently doesn't compile.

So short of dirtying up my model by creating a new getter to just negate this value (the view should NOT dictate whats in you're model!!!), is there anything else I can do?

Best Answer

Save yourself some trouble and enlist the help of jQuery:

<apex:page>
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"/>
    <input type="checkbox" disabled="true" />
    <input type="checkbox" disabled="true" class="{!if(model.myBoolean,'','chk')}"/>

    <script>
        $('.chk').attr('checked','');
    </script>
</apex:page>

The problem you are having is that HTML does not care what the value of checked is, as long as it is present on the element it will be displayed as checked.

Visualforce will not allow you to compile unless you have values associated with each attribute, this is why your IF merge would not compile

Also, the selected attribute of the inputCheckbox does not allow you to use dynamic value. Another you thought it was going to be easy but SF quirk got in the way

Error: Unknown property 'if(true,'true','false')'

So you are in a catch 22. jQuery/JS is easiest or render based on value using panels:

<apex:outputPanel rendered="{!model.myBoolean}">
   <input type="checkbox" disabled="true" />
</apex:outputPanel>
<apex:outputPanel rendered="{! !model.myBoolean}">
  <input type="checkbox" disabled="true" checked='true' />
</apex:outputPanel>

Simplified version

this is implementation simplified with add ONE line

<apex:page>

    <input type="checkbox" disabled="true" class="{!if(model.myBoolean,'','chk')}"/>

    <script>
        document.getElementsByClassName("chk")[0].setAttribute('checked','');
    </script>

</apex:page>
Related Topic