6

In JSF's tag, if you feed it using a Map<Key, Value>

<h:selectOneMenu value="#{bean.integerProperty}">
  <f:selectItems value="#{bean.mapProperty}"/>
</h:selectOneMenu>

The resulting HTML will be the inverse of what one would expect

<select>
  <option selected="selected" value="MapValue1">MapKey1</option>
  <option value="MapValue2">MapKey2</option>
  <option value="MapValue3">MapKey3</option>
</select>

In the sense that the map's value will be set in the option's value attribute and the key will be set in its label.

I found this JIRA JIRA 1808 where the implications of having to write wrong maps are explained (uniqueness, mostly), but don't quite understand why correcting this would be

'disruptive and backwards incompatible'.

Does this come from previous versions of JSF? If so, does anybody know if there's a reason for it to be like this?

Just curious about if there's an explanation not to fix this.

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
comandante N
  • 276
  • 2
  • 5
  • 11

1 Answers1

11

The initial reasoning is after all rather simple: dropdown labels have a greater precedence of to be unique than dropdown values. A dropdown with two same labels would be more a "wtf?" for the enduser than a dropdown with two same values. Map keys ensure uniqueness. I have indeed ever reported the technical unintuitiveness in the issue report which you linked yourself. However, it's a WONTFIX. If it would be changed in JSF 2.2, it wouldn't be backwards compatible anymore with JSF 2.0 / 2.1.

If your environment supports EL 2.2 (Tomcat 7, Glassfish 3, etc), you can easily swap it as follows:

<h:selectOneMenu value="#{bean.integerProperty}">
  <f:selectItems value="#{bean.mapProperty.entrySet()}" var="entry" 
     itemValue="#{entry.key}" itemLabel="#{entry.value}" />
</h:selectOneMenu>

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Calling the entrySet from EL returns no values in JBoss 6 using Mojarra 2.0.3. (wihich should support EL2.2., shouldn't it?). I had tried the itemValue and itemLabel trick before, using directly the Map as the selectItems' value but keys and labels were still inverted. My question is conceptually answered anyway so thanks for the quick response. – comandante N Mar 27 '12 at 17:40
  • JBoss 6 indeed supports EL 2.2. Make sure that `web.xml` root declaration conforms Servlet 3.0 and not Servlet 2.5, or it will run in fallback Servlet 2.5 / EL 2.1 modus. – BalusC Mar 27 '12 at 17:45