What is a JSF component binding? How can I use it?

Standard

One of the more flexible features of Java Server Faces is the ability to use bindings within a view. Most developers omit the binding attribute and rely on a component libraries magic to display errors to the end user. Using the JSF binding component it is possible to specify the binding view component name for the UIComponent in the java backing bean. This binding refers to an instance of UIComponent in the EL scope allowing you to access certain properties #{mybinding.clientId}, #{mybinding.value},  #{mybinding.valid},  #{mybinding.submittedValue}

For example, lets assume you have a selectOneMenu with a list of items. These items are U.S states, then below you have a inputText area where the end user enters his/her city. We do not want to allow them to enter a city that is not in a state.

The problem can be solved using bindings. Consider this solution that binds the selected state value to the city entered. When submitted the validator will have access to both components.

The View

Backing validator

Using bindings as described provides a solution for more complex validation requirements.

Using bindings with Bootstrap 3

Arguably the most popular css library out is Boostrap 3. It provides a sleek look to web pages. Using component bindings you can easily marry JSF with Bootstrap CSS. This is because components have a isValid EL expression attached to them.

For example lets assume you have a inputText that requires a min length of 4 and a max of 6. If outside of that requirement you want the field to be marked as invalid.

To highlight invalid fields use the binding component together with a form-group. The form-group has a has-error CSS class that will highlight the field inside. Once the inputText validation fails and refreshes the screen it will call the EL expression #{name.valid} and render the has-error class.

Whats the difference between #{mybinding.value} and  #{mybinding.submittedValue}?

This can be answered by understanding that the order of components matters. JSF will process your components in the order they appear in the view. The backing javascript for JSF does this. So for example if I was to swap the order of my state / city example so that the selectOneMenu came after the city inputText I would need to use the bindings submittedValue as ordering would cause the binding to be empty on the validator.