Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF Tree in a dropdown

I want to display a tree like structure in my dropdown in JSF. Basically the select items are in a hierarchy and I would like that to be evident in the dropdown.

Is it possible ?

like image 459
Anand Sunderraman Avatar asked Nov 18 '10 11:11

Anand Sunderraman


1 Answers

So, you basically want a HTML <optgroup>? Use SelectItemGroup.

JSF bean (I assume JSF 1.x):

private String option; // +getter +setter
private List<SelectItem> options; // +getter

public Bean() {
    options = new ArrayList<SelectItem>();

    SelectItemGroup group1 = new SelectItemGroup("Group 1");
    group1.setSelectItems(new SelectItem[] {
        new SelectItem("Group 1 Value 1", "Group 1 Label 1"),
        new SelectItem("Group 1 Value 2", "Group 1 Label 2"),
        new SelectItem("Group 1 Value 3", "Group 1 Label 3")
    });
    options.add(group1);

    SelectItemGroup group2 = new SelectItemGroup("Group 2");
    group2.setSelectItems(new SelectItem[] {
        new SelectItem("Group 2 Value 1", "Group 2 Label 1"),
        new SelectItem("Group 2 Value 2", "Group 2 Label 2"),
        new SelectItem("Group 2 Value 3", "Group 2 Label 3")
    });
    options.add(group2);
}

JSF view:

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

Generated HTML example:

<select name="j_idt6:j_idt7" size="1">
    <optgroup label="Group 1">
        <option value="Group 1 Value 1">Group 1 Label 1</option>
        <option value="Group 1 Value 2">Group 1 Label 2</option>
        <option value="Group 1 Value 3">Group 1 Label 3</option>
    </optgroup>
    <optgroup label="Group 2">
        <option value="Group 2 Value 1">Group 2 Label 1</option>
        <option value="Group 2 Value 2">Group 2 Label 2</option>
        <option value="Group 2 Value 3">Group 2 Label 3</option>
    </optgroup>
</select>

How it look like in browser:

alt text

like image 125
BalusC Avatar answered Oct 02 '22 14:10

BalusC