I want to make a selectOneMenu dropdown so I can select a status on my question. Is it possible to make the f:selectItem more flexible considering what happens if the order of the enums changes, and if the list was large? And could I do this better? And is it possible to automatically "select" the item that the question have?
Enum class
public enum Status {
SUBMITTED,
REJECTED,
APPROVED
}
Question entity
@Enumerated(EnumType.STRING)
private Status status;
JSF
<div class="field">
<h:outputLabel for="questionStatus" value="Status" />
<h:selectOneMenu id="questionStatus" value="#{bean.question.status}" >
<f:selectItem itemLabel="Submitted" itemValue="0" />
<f:selectItem itemLabel="Rejected" itemValue="1" />
<f:selectItem itemLabel="Approved" itemValue="2" />
</h:selectOneMenu>
<hr />
</div>
For localization we can use also this solution:
So the resource path for localization strings are not hardcoded in Enum.
You could use
<f:selectItems value="#{carBean.carList}" />
and return a list ofSelectItem
instances that wrap the enum (useStatus.values()
to get all possible values).JSF has a builtin converter for
enum
, so this should do:with
(note: since JSF 2.0 there's no need anymore to provide a
SelectItem[]
orList<SelectItem>
, aT[]
andList<T>
are accepted as well and you can access the current item byvar
attribute)If you happen to use JSF utility library OmniFaces, then you could use
<o:importConstants>
instead of a bean.If you intend to control the labels as well, you could add them to the
Status
enum:with
Or, better, make the enum value a property key of a localized resource bundle (EL 3.0 required):
with this in a properties file associated with resource bundle
#{text}
You can use following utility el function to obtain the enum values and use them in a
SelectOneMenu
for example. No need to create beans and boilerplate methods.Register it as an el function in a taglib file:
And finally call it like:
Similiar to BalusC answer you should be using a resource bundle with localized enum labels and for cleaner code you can also create a function like
getEnumLabel(enum)