djmj
djmj

Reputation: 5544

selectOneMenu with Date using different pattern for value and label

I want to build a Weekday select menu. Weekdays are initialized to first weekday of year 1970.

The converter converts the value to a date. But I want to display the full text weekday using java date pattern "EEEE".

<h:selectOneMenu id="day" label="#{msg.day_u}" required="true" value="#{date}">
    <f:convertDateTime pattern="dd/mm/yyyy"/>
    <f:selectItem itemValue="05/01/1970" itemLabel="display Monday using pattern"/>
    <!-- other weekdays -->
</h:selectOneMenu>

This is not working. Right now I am using a custom EL function to retrieve a localized weekday in the label attribute.

Is there a way to use it with a date pattern?

Upvotes: 2

Views: 4056

Answers (1)

BalusC
BalusC

Reputation: 1109062

The converter will indeed not be applied on the option label. It's only applied on the option value. It should work just fine with an EL function. Assuming that you've a List<Date> as available items and Date as selected item, then this should do:

<f:selectItems value="#{bean.weekdays}" var="day" 
    itemValue="#{day}" itemLabel="#{util:formatDate(day, 'EEEEE')}" />

where formatDate() look like this

public static String formatDate(Date date, String pattern) {
    if (date == null) {
        return null;
    }

    if (pattern == null) {
        throw new NullPointerException("pattern");
    }

    Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
    return new SimpleDateFormat(pattern, locale).format(date);
}

OmniFaces has by the way exactly this function.

Upvotes: 2

Related Questions