Using Java enums as SelectItems
Since Java 5.0, enumerations are very common in J2EE application as a replacement for constants and enumerations. They are very powerful because you can use them as normal classes and they express in a very clean manner your business model constant types. For example, you can have the following very simple enum to describe payment options for your e-commerce website:
public enum PaymentType
{
MONEY_ORDER,
VISA,
MASTERCARD,
PAYPAL;
}
As a matter of fact, it would be very useful to use them in your JSF page code. Guess what, it is supported by the default converter of SelectItems in JSF 1.2 (I don’t know if previous version of JSF supported them). This mean you can strongly type your value in the bean that holds your JSF component selected value. For example:
public class PaymentController
{
public void setPaymentType(PaymentType type) { this.type=type; }
public void getPaymentType() { return this.type; }
}
And therefore can use something like this in your page:
<af:selectOneChoice label="Payment type : " value="#{pageFlowScope.paymentController.paymentType}">
<f:selectItems value="#{pageFlowScope.paymentController.paymentTypes}"/>
</af:selectOneChoice>
Then, just create a function that generate your SelectItem list from an enum type:
public class PaymentController
{
...
public List<SelectItem> getPaymentTypes()
{
List<SelectItem> items = new ArrayList<SelectItem>();
for (PaymentType type: PaymentType.values())
{
items.add(new SelectItem(type, type.toString()));
}
return items;
}
...
}
You can now add types to your enum and your UI will automatically support them. Another thing you can do is that instead of calling type.toString() as a SelectItem label, you can use a ressource bundle to specify for each of your enum values a key and a label and format them using the user’s current locale.
Thanks for the post. Exactly what I was looking for.
Do you know if there is a way to define a generic provider for enum values to be used as a source of the f:selectItems element in JSF 2.0?
Hi Simon, thanks for visiting my blog.
I’m not familiar with JSF 2.0 yet as I am still using 1.2.
For your question, I don’t really know what you meant by a “generic provider”.
The most generic way to go I found is:
<E extends Enum> List selectItemsFromEnumValues(E[] values)
and then, you just use it by calling .values() on the enum used. I tried to pass in the enum class type as an argument, but I didn’t found a way to retrieve the enum values.
Regards,
JP
just as what i’m looking for
regards,
ikren