How to use PrimeFaces SelectOneMenu ItemLabel & ItemValue with Lists?

java, jsf, primefaces

Solution

Use `<c:forEach>` to generate `<f:selectItem>` components. You can use its `varStatus` attribute to get the current iteration index, so that you can get an item of the other list by index.

<c:forEach items="#{playerManager.playerIds}" var="playerId" varStatus="loop">
    <f:selectItem itemValue="#{playerId}" itemLabel="#{playerManager.playerNames[loop.index]}" />
</c:forEach>

Note that when the `#{playerManager}` is view scoped, this construct would then recreate the bean on every postback. See also JSTL in JSF2 Facelets... makes sense?

Problem

As far as im aware the correct way to display information in a SelectOneMenu is by having a list of objects and using it's properties like so: ``` <p:selectOneMenu id="player" value=""> <f:selectItem itemLabel="Select" itemValue="" /> <f:selectItems value="#{players}" var="player" itemLabel="#{player.name}" itemValue="#{player.id}"/> </p:selectOneMenu> ``` but what if I dont have a list of players, what if I have something like this? I'd like to get it to work like this: ``` //PlayerManager public List<String> getPlayerNames() { String[] names = new String[] {"player1", "player2"}; return Arrays.asList(names); } public List<String> getPlayerIds() { String[] ids = new String[] {"1", "2"}; return Arrays.asList(ids); } <p:selectOneMenu id="player" value=""> <f:selectItem itemLabel="Select" itemValue="" /> <f:selectItems value="#{playerManager.playerNames}" var="player" itemLabel="#{playerManager.playerNames}" itemValue="#{playerManager.playerIds}"/> </p:selectOneMenu> ```

Original source

Related problems