Conditional binding attribute in Facelet tag file/JSF

204 Views Asked by At

In my JSF 2.1 project i defined a custom tag file which includes a h:inputText element. This element may or may not include a binding attribute – depending on the passed parameters of the custom element.

Example formInput.xhtml (excerpt):

<h:inputText id="#{id}" value="#{value}">
    <c:if test="#{not empty binding}">
        <f:attribute name="binding" value="#{binding}"/>
    </c:if>
</h:inputText>

Usage from other file:

<e:formInput id="test" value="#{testBean.myValue}" binding="#{testBean.myBinding}"/>

Unfortunately this doesn't work. #{not empty binding} resolves to false and the binding is not applied.

However, defining the binding attribute without a condition does work. Example:

<h:inputText id="#{id}" value="#{value}">
    <f:attribute name="binding" value="#{binding}"/>
</h:inputText>

In this case the binding is applied correctly.

Does anyone know how to set the binding conditionally?

1

There are 1 best solutions below

0
On

In my opinion using binding is a hack. My advice would be to solve your underlaying problem differently. That being said, there is a workaround for your conditional binding issue, using "brace notation" and a fallback binding object. Instead of passing the object to bind to, pass it's name (a String), this allows you to bind it like:

<h:inputText binding="#{testBean[objectName]}"/>

Brace notation also makes it possible to conditionally pass a property:

<h:inputText binding="#{testBean[empty objectName ? 'fallback' : objectName]}"/>

This requires you to have a fallback binding object available at #{testBean.fallback}.

See also: