3

Why is my List<Date> not getting converted? The <p:selectOneMenu> items pattern looks like Thu Mar 01 00:00:00 BRT 2012 instead of the desired "MM/yyyy".

<p:selectOneMenu value="#{report003.selectedMes}">
  <p:ajax update="pesquisaThomas" listener="#{report003.loadPesquisa()}" />
  <f:selectItem itemLabel="[Todos]" itemValue="" />
  <f:convertDateTime pattern="MM/yyyy" />
  <f:selectItems value="#{report003.pesquisaMeses}" />
</p:selectOneMenu>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
BBacon
  • 2,456
  • 5
  • 32
  • 52
  • Please edit and improve your question. You forgot to elaborate "doesn't work". What exactly did you expect? What exactly happens instead? Didn't it show the labels(!) the way you expeceted? Or did it generate a conversion or validation error? – BalusC Sep 26 '12 at 14:45

2 Answers2

4

The conversion applies to the item value only, not to the item label. The label is just presented using the default Date#toString() pattern.

Your best bet is either creating a List<SelectItem> instead of List<Date> wherein you convert the item labels yourself,

List<Date> availableDates = ...;
List<SelectItem> selectItems = ...;
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");

for (Date availableDate : availableDates) {
    selectItems.add(new SelectItem(availableDate, sdf.format(availableDate)));
}

or using <f:selectItems var> with an EL function in the itemValue. For example, the OmniFaces of:formatDate() (or homegrow one).

<f:selectItems value="#{bean.availableDates}" var="date" 
    itemValue="#{date}" itemLabel="#{of:formatDate(date, 'MM/yyyy')}" />

This problem is by the way not specific to <p:selectOneMenu>, you would have exactly the same problem when using the standard <h:selectOneMenu>.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Try this:

managed bean

private SimpleDateFormat sdf;
(...)

@PostConstruct
public void init(){
    sdf = new SimpleDateFormat("MM/yyyy");
}

public SimpleDateFormat getSdf(){
    return sdf;
}

public void setSdf(SimpleDateFormat sdf){
    this.sdf = sdf;
}

xhtml

<p:selectOneMenu value="#{report003.selectedMes}">
    <p:ajax update="pesquisaThomas" listener="#{report003.loadPesquisa()}" />
    <f:selectItem itemLabel="[Todos]" itemValue="" />
    <f:selectItems value="#{report003.pesquisaMeses}"
                   var="mes" itemValue="#{mes}"
                   itemLabel="#{myMB.sdf.format(mes)}" />

Rogério Arantes
  • 712
  • 1
  • 8
  • 29