1

All the questions asking: how can I bind POJOs to h:selectXX with f:selectItems end up with answer "use a converter". However, it seems it is possible to go without the converter - see:

Facelet:

<h:selectManyListbox value="#{pojoBean.selected}">
    <f:selectItems value="#{pojoBean.allItems}" var="i" itemValue="#{i}" itemLabel="#{i.txt}" />
</h:selectManyListbox>

Bean:

public class PojoBean {
    List<MyItem> selected;
    List<MyItem> allItems;

POJO:

public class MyItem {
    private String txt;
...}

Note that this seems to work only with h:selectManyListbox, when the value/s being selected end up in a list, not in a single property.

Question - why doesn't it work with h:selectOneMenu and etc?

jarek.jpa
  • 565
  • 1
  • 5
  • 18

1 Answers1

0

Likely your MyItem class has already the toString() overridden which returns the txt and you were plain printing selected as follows to determine the selected values:

System.out.println(selected);

Try to cast each item of selected back to MyItem:

for (MyItem myItem : selected) {
    System.out.println(myItem);
}

You'll see that it fails with ClassCastException, because it's actually a String. So yes, you still need a converter here.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Damn, you're right :) I was actually printing with an EL in the view (refreshed with an f:ajax), the MyItem has toString overriden by standard Eclipse toString-generation. When I tried the foreach you mentioned it is really throwing ClassCastExceptions! Question comes how could a List be passed to a List parameter, but as I understand it's about generics here - the MyItem type parameter gets lost and that's why JSF is able to pass there anything (i.e. String). THANKS! – jarek.jpa Sep 14 '11 at 19:31
  • That's answered in the "see also" link. JSF/EL isn't at all aware about the generic type of the `List` because that's by design completely lost during runtime. All JSF/EL knows is that it's a `List` and since there's no converter, it just adds unmodified/unconverted `String` submitted values to the `List`. – BalusC Sep 14 '11 at 19:31