How to use enum values in f:selectItem(s)
JSF has a builtin converter for enum
, so this should do:
@ManagedBean
@ApplicationScoped
public class Data {
public Status[] getStatuses() {
return Status.values();
}
}
with
<h:selectOneMenu value="#{bean.question.status}" >
<f:selectItems value="#{data.statuses}" />
</h:selectOneMenu>
(note: since JSF 2.0 there's no need anymore to provide a SelectItem[]
or List<SelectItem>
, a T[]
and List<T>
are accepted as well and you can access the current item by var
attribute)
If you happen to use JSF utility library OmniFaces, then you could use <o:importConstants>
instead of a bean.
<o:importConstants type="com.example.Status" />
<h:selectOneMenu value="#{bean.question.status}" >
<f:selectItems value="#{Status}" />
</h:selectOneMenu>
If you intend to control the labels as well, you could add them to the Status
enum:
public enum Status {
SUBMITTED("Submitted"),
REJECTED("Rejected"),
APPROVED("Approved");
private String label;
private Status(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
with
<f:selectItems value="#{data.statuses}" var="status"
itemValue="#{status}" itemLabel="#{status.label}" />
Or, better, make the enum value a property key of a localized resource bundle (EL 3.0 required):
<f:selectItems value="#{data.statuses}" var="status"
itemValue="#{status}" itemLabel="#{text['data.status.' += status]}" />
with this in a properties file associated with resource bundle #{text}
data.status.SUBMITTED = Submitted
data.status.REJECTED = Rejected
data.status.APPROVED = Approved
For localization we can use also this solution:
public enum Status { SUBMITTED, REJECTED, APPROVED }
data.status.SUBMITTED=Submitted
data.status.REJECTED=Rejected
data.status.APPROVED=Approved
<h:selectOneMenu value="#{bean.question.status}" >
<f:selectItems
value="#{data.statuses}"
var="status"
itemValue="#{status}"
itemLabel="#{text['data.status.'.concat(status)]}" />
</h:selectOneMenu>
So the resource path for localization strings are not hardcoded in Enum.
You could use <f:selectItems value="#{carBean.carList}" />
and return a list of SelectItem
instances that wrap the enum (use Status.values()
to get all possible values).