如何在更改 h:selectOneMenu 时加载和显示相关的 h:selectOneMenu [英] How to load and display dependent h:selectOneMenu on change of a 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?
最好的祝福.
推荐答案
您可以使用
来解决这个问题.当嵌套在诸如
之类的输入组件中时,默认情况下会在输入值更改时调用它.您可以指定一个 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
而不是 List
.映射键成为选项标签,映射值成为选项值.您只需要记住 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屋!