2

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
  • 3,016
  • 9
  • 43
  • 74
  • 1
    `function`? Is that Java or JavaScript? The `String[]` is by the way not a list, but an array. Please get the terms right and post compilable code to avoid red herrings. – BalusC Apr 04 '13 at 15:37
  • @BalusC sorry was meant to be Java. Fixed now. The reason I need it the second way is because im trying to populate a selectmenu whose values don't come from a database. Hope that makes sense. – Jonathan Apr 04 '13 at 15:41
  • `function` doesn't exist in Java. You're mixing Java with JavaScript. – BalusC Apr 04 '13 at 15:42
  • @BalusC Sorry about that, Yeah I was thinking in pseudocode and was making an example off the top of my head. – Jonathan Apr 04 '13 at 15:44

1 Answers1

7

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?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    Thanks! Is there a way to use this solution and allow the setting of a default value? `` – Jonathan Apr 04 '13 at 15:58
  • 1
    Set 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. – BalusC Apr 04 '13 at 16:00