How to preselect an option of h:selectOneMenu

Ionut picture Ionut · Jan 16, 2012 · Viewed 7.6k times · Source

Is it possible to preselect one of the options from the select menu?

I have this UI Component:

<h:selectOneMenu value="#{authenticateController.country}">
    <f:selectItems value="#{constants.countrySelectMenu}" />
</h:selectOneMenu>

The values of #{constants.countrySelectMenu} are a list of country ID - country name pairs. Is there a way to render the list with a preselected value or at least is there a work-around to get this done?

Answer

BalusC picture BalusC · Jan 16, 2012

Just preset the property behind <h:selectOneMenu value> with the desired value. You can do it in for example the bean's (post)constructor, action(listener) method, etc.

In your specific example, thus e.g.

public class AuthenticateController {

    private String country;

    @PostConstruct
    public void init() {
        country = "NL";
    }

    // ...
}

It works exactly the same way for all other UIInput components like <h:inputText> and so on. The input component's value itself simply represents the (pre)selected/checked/filled value.

See also: