custom boolean converter to set style class

386 views Asked by At

A Converter is defined in faces-config.xml which changes a boolean into a String "Yes" or "No"

<converter>
    <converter-id>booleanConverter</converter-id>
    <converter-class>com.example.BooleanConverter</converter-class>
</converter>

This works fine using

<h:outputText value="#{bean.booleanValue}" converter="booleanConverter" />

But if the intention was to style a surrounding div element is this possible using a converter? For example if a Converter was defined which return String "booleanTrue" and "booleanFalse" (which are defined in CSS)

<converter>
    <converter-id>booleanStyleConverter</converter-id>
    <converter-class>com.example.BooleanStyleConverter</converter-class>
</converter>

Could I do something like:

<div class="#{booleanStyleConverter.getAsString(null,null,bean.booleanValue)}">
    <h:outputText value="#{bean.booleanValue}" converter="booleanConverter" />
</div>

Defining in backing bean works but seems unsatisfactory

public String booleanStyle(boolean value) {
    BooleanStyleConverter bsc = new BooleanStyleConverter();
    return bsc.getAsString(null, null, value);
}
1

There are 1 answers

4
kolossus On BEST ANSWER

The whole point of the converter is to change the value that's saved to the backing bean into something desirable. Why are you not just using class="#{bean.booleanValue}"?

Or even simpler still : class="textBox.value eq 'true'? 'booleanTrue': 'booleanFalse'", where textBox is the binding of the textbox:

<div class="#{textBox.value eq 'true'? 'booleanTrue': 'booleanFalse'}">
    <h:outputText binding="#{textBox}" id="textBox" value="#{bean.booleanValue}"/> 
</div>