HTML and CSS Reference
In-Depth Information
Listing 4-14. CountryValueChangeListener Custom Listener
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
public class CountryValueChangeListener implements ValueChangeListener {
@Override
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
FacesContext context = FacesContext.getCurrentInstance();
Country country = context.getApplication().evaluateExpressionGet(context,
"#{country}",
Country.class);
String selectedCountryName = (String) event.getNewValue();
if ("USA".equals(selectedCountryName)) {
country.setCapital("Washington");
} else if ("Egypt".equals(selectedCountryName)) {
country.setCapital("Cairo");
} else if ("Denmark".equals(selectedCountryName)) {
country.setCapital("Copenhagen");
}
}
}
In order to attach the custom value change listener to the ValueHolder (or EditableValueHolder ) component,
you can use the <f:valueChangeListener> tag inside the component. Listing 4-15 shows the updates on the capital
finder form mentioned in Listing 4-13 with the custom value change listener update.
Listing 4-15. An Example of Custom Value Change Listener in the XHTML Page
<h:form>
<h:outputLabel for="countries" value="Select a country: "/>
<h:selectOneMenu id="countries" value="#{country.name}"
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"/>
<f:valueChangeListener type="com.jsfprohtml5.factorial.model
.CountryValueChangeListener"/>
</h:selectOneMenu> <br/>
<h:outputText value="Capital of #{country.name} is #{country.capital}"
rendered="#{country.capital ne null}"/>
</h:form>
Search WWH ::




Custom Search