6

I'm creating a List of javax.faces.model.SelectItem (in a bean) for use with a h:selectManyCheckbox but I cannot figure out how to make a SelectItem selected.

How to do this? Must be possible, right?...

    public List<SelectItem> getPlayerList(String teamName) {
    List<SelectItem> list = new ArrayList<SelectItem>();

    TeamPage team = (TeamPage) pm.findByName(teamName);

    List<PlayerPage> players = pm.findAllPlayerPages();

    for (PlayerPage player : players) {
        boolean isMember = false;
        if (team.getPlayerPages().contains(player)) {
            isMember = true;
        }
        SelectItem item;
        if (isMember) {
            // TODO: Make SelectItem selected???
            item = null;
        } else {
            item = new SelectItem(player.getId(), createListItemLabel(player), "", false, false);
        }
        list.add(item);         
    }
    return list;
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
mafro
  • 865
  • 1
  • 10
  • 11

2 Answers2

9

Assume we have this JSF code:

<h:selectManyCheckbox value="#{bean.selectedValues}">
    <f:selectItems value="#{bean.playerList}"/>
</h:selectManyCheckbox>

then the selected values (i.e. the checked checkboxes) are stored in the bean.selectedValues property.

Thus, in your Java code, you must handle the selectValues by putting the correct ID in the selectedValues property.

Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
-1

If anybody is working with selectOneMenu and populating elements dynamically: While creating a SelectItem, if you provide some value(first parameter) as follows:

new SelectItem("somevalue", "someLabel", "someDescription", false, false);

It translates to this in the html:

<option value="somevalue">someLabel</option>

If you do not provide a value as follows:

new SelectItem("", "someLabel", "someDescription", false, false);

, it translates to this

<option value="" selected="selected">someLabel</option>

Hence if you want an element to be the default on page load(like "Select one of these"), do not provide a value. If you create more than one element without a value, any one of them are chosen for default on page load(probably preference based on ascending alphabetical order).

  • 1
    I think your answer is not for this question. It's more an answer for https://stackoverflow.com/questions/11360030/best-way-to-add-a-nothing-selected-option-to-a-selectonemenu-in-jsf and that already has a good (much better) answer than yours. – Kukeltje Sep 02 '19 at 10:49