How to use PrimeFaces SelectOneMenu ItemLabel & ItemValue with Lists?
19,672
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?
Author by
Jonathan
Updated on June 13, 2022Comments
-
Jonathan almost 2 years
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>
-
Jonathan about 11 yearsThanks! Is there a way to use this solution and allow the setting of a default value?
<p:selectOneMenu id="player" value="2">
-
BalusC about 11 yearsSet it in the property behind the
value
attribute:value="#{playerManager.selectedPlayerId}"
. No, it can't be a static string, it must be writable. Otherwise, use JavaScript to set it via its widget variable during page load.