So, we have a menu, brimmed with our objects from list/database. The intention would be creating a default “Select” kind of the first row and to brag on the user when s/he selects the default.
The trick is simple, create the first list with null object and label it as Select. Lets show it with simple example.
We want to have a list of programming languages on our select menu. And, the first would be a default object.
//Actual domain class
class Language{
private String name;
private String type;
private boolan isCompiled;
getters/setters goes here
}
//Bean class
class someBean{
private List languages;
.
.
public String getLanguages(){
//Let languages would be filled by some service or factory
this.languages = someLanguageFactory.getAllLanguages();
//Assign the first element as null
this.languages.add(0, null);
}
}
//JSF page
:
:
<h:selectOneMenu id="selectLanguage" value="someBean.languages"
requred="true" ....
This should do the task, make the list required, and populate the first list null. So, during validation if the selection is null it would be rejected as we have told it to watch an eye on blank fields.