如何在更改h:selectOneMenu时加载和显示依赖的h:selectOneMenu [英] How to load and display dependent h:selectOneMenu on change of a h:selectOneMenu

查看:129
本文介绍了如何在更改h:selectOneMenu时加载和显示依赖的h:selectOneMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建JSF注册表单,该表单具有包含所有国家/地区列表的选择菜单.我知道这很容易用Java HashMap来实现,但是我不知道如何实现的棘手部分是用户从列表中选择了他的国家之后,第二选择菜单随其国家的城市一起出现了. ?有什么有用的例子吗?

I want to create JSF registration form which has select menu with the list of all countries. I know that this is easy for implementation with Java HashMap but the tricky part that I don't know how to implement is how right after the user selects his country from the list, second select menu to appear with the cities in his country? Is there any useful example?

最良好的祝愿.

推荐答案

您可以为此使用<f:ajax>.当嵌套在诸如<h:selectOneMenu>之类的输入组件中时,默认情况下将在更改输入值时调用它.您可以指定一个listener方法,该方法可以根据当前输入值预填充下一个组件的数据,并且可以在render中指定该下一个组件的客户端ID,以显示预填充的数据.

You can use <f:ajax> for this. When nested in an input component such as <h:selectOneMenu>, then it will by default be invoked when the input value is changed. You can specify a listener method which could prepopulate the data for the next component based on the current input value, and you can specify the client ID of that next component in render in order to show the prepopulated data.

<h:selectOneMenu value="#{bean.country}">
    <f:selectItems value="#{bean.countries}" />
    <f:ajax listener="#{bean.changeCountry}" render="cities" />
</h:selectOneMenu>
<h:panelGroup id="cities">
    <h:selectOneMenu value="#{bean.city}" rendered="#{not empty bean.cities}">
        <f:selectItems value="#{bean.cities}" />
    </h:selectOneMenu>
</h:panelGroup>

bean必须至少在视图范围内(不是请求范围):

The bean must be in at least the view scope (not request):

@ManagedBean
@ViewScoped
public class Bean implements Serializable {

    private String country; // +getter+setter
    private String city; // +getter+setter
    private List<String> countries; // +getter
    private List<String> cities; // +getter

    @EJB
    private LocationService locationService;

    @PostConstruct
    public void init() {
        countries = locationService.getCountries();
    }

    public void changeCountry() {
        cities = locationService.getCities(country);
    }

    // ...
}

您当然也可以使用Map<String, String>代替List<String>.映射键成为选项标签,映射值成为选项值.您只需要记住HashMap本质上是无序的.您希望使用LinkedHashMap代替以Map插入顺序显示项目.

You can of course also use a Map<String, String> instead of a List<String>. The map key becomes the option label and the map value becomes the option value. You only need to keep in mind that a HashMap is by nature unordered. You'd prefer using LinkedHashMap instead to display the items in Map insertion order.

  • Our selectOneMenu wiki page
  • When to use valueChangeListener or f:ajax listener?

这篇关于如何在更改h:selectOneMenu时加载和显示依赖的h:selectOneMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆