Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

jsf - How to load and display dependent h:selectOneMenu on change of a h:selectOneMenu

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?

Best wishes.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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);
    }

    // ...
}

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.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...