HTML and CSS Reference
In-Depth Information
public void findCapital(ValueChangeEvent event) {
System.out.println("Old selected value is: " + event.getOldValue());
System.out.println("New selected value is: " + event.getNewValue());
String selectedCountryName = (String) event.getNewValue();
if ("USA".equals(selectedCountryName)) {
capital = "Washington";
} else if ("Egypt".equals(selectedCountryName)) {
capital = "Cairo";
} else if ("Denmark".equals(selectedCountryName)) {
capital = "Copenhagen";
}
}
}
As you notice in the bolded lines, the value change listener method returns void and has
ValueChangeEvent
as
a parameter. Using
getOldValue()
and
getNewValue()
methods of
ValueChangeEvent
, you can get the old and the
new values of the
ValueHolder
(or
EditableValueHolder
) components. In our example, we get the new value which
represents the new country selection, then get the suitable capital for the selected country, and finally set the result in
the
capital
attribute in order to be displayed by the page, as shown in Listing 4-11.
Instead of firing the value change event by changing the value of the
ValueHolder
(or
EditableValueHolder
)
component and click on a
CommandButton
or a
CommandLink
. You can fire the value change event when the value of
the
ValueHolder
(or
EditableValueHolder
) component changes by submitting the form when the component's value
changes. Listing 4-13 shows how to apply this behavior by removing the
CommandButton
and submitting the form on
value change.
Listing 4-13.
Executing the Value Change Listener by Submitting the Form on SelectOneMenu's Value Change
<h:form>
<h:outputLabel for="countries" value="Select a country: "/>
<h:selectOneMenu id="countries" value="#{country.name}"
valueChangeListener="#{country.findCapital}"
onchange="submit();"
>
<f:selectItem itemLabel="---" itemValue="---"/>
<f:selectItem itemLabel="United States" itemValue="USA"/>
<f:selectItem itemLabel="Egypt" itemValue="Egypt"/>
<f:selectItem itemLabel="Denmark" itemValue="Denmark"/>
</h:selectOneMenu> <br/>
<h:outputText value="Capital of #{country.name} is #{country.capital}"
rendered="#{country.capital ne null}"/>
</h:form>
Adding to using the default value change listener, you can write your own custom value change listener. This
can be done by creating a custom value change listener class that implements
ValueChangeListener
interface.
Listing 4-14 shows
CountryValueChangeListener
, which utilizes
ValueChangeListener
and implements
processValueChange()
, which gets the new selected country and then finds its capital and finally sets the result in the
capital
attribute of the
Country
managed bean.