how to use value change listener

余生长醉 提交于 2019-12-06 09:06:46
BalusC

Is this new EventsBean().setCapital(capital);right ?

No, it is not right. You're manually creating a brand new instance instead of using the one which is managed by JSF. Your instance would totally disappear once the method finishes and returns. You should instead be setting the capital in the instance which is managed by JSF. There are several ways to achieve this. If you really intend to use the ValueChangeListener this way (which is rather strange for this particular purpose by the way), then you need to fix it as follows:

FacesContext context = FacesContext.getCurrentInstance();
EventsBean eventsBean = context.getApplication().evaluateExpressionGet(context, "#{event}", EventsBean.class);
eventsBean.setCapital(capital);

Easier would be to do the job just in the EventsBean itself.

<h:selectOneMenu value="#{event.country}" valueChangeListener="#{event.changeCountry}" onchange="submit()">
    <f:selectItems value="#{event.countries}"/>     
</h:selectOneMenu>
Capital: #{event.capital}
private String country;
private String capital;
private Map<String, String> capitals;

@PostConstruct
public void init() {
    capitals = new HashMap<>();
    capitals.put("Egypt", "Cairo");
    capitals.put("Kuwait", "Kuwait");
    capitals.put("United States", "Washington D.C.");
}

public void changeCountry(ValueChangeEvent event) {
    capital = capitals.get(event.getNewValue());
}

Or, since you're already using JSF 2.0, much better is to use <f:ajax>. It does the right job at the right moment. (Ab)using the valueChangeListener the way as in your original code is actually a leftover of the JSF 1.x era.

<h:selectOneMenu value="#{event.country}">
    <f:selectItems value="#{event.countries}"/>     
    <f:ajax listener="#{event.changeCountry}" render="capital" />
</h:selectOneMenu>
Capital: <h:outputText id="capital" value="#{event.capital}" />
// ...

public void changeCountry() {
    capital = capitals.get(country);
}

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!