Primefaces树复选框单选

时间:2014-02-24 19:52:54

标签: checkbox primefaces tree selection

我需要在“复选框”选择模式下使用primefaces树,但一次只能选择一个且只能选择一个节点。默认情况下,primefaces树在选择节点时选择所有后代,这实际上是我想要更改的内容。

有人可以帮我搞清楚吗?

1 个答案:

答案 0 :(得分:2)

我终于通过查看Javascript source code of the tree找到了实现这一目标的方法。你可以,例如创建一个缓存先前选定节点的单例。通过使用树的“onNodeClick”属性,您可以调用Javascript函数,该函数在窗口小部件内部设置新选定节点之前取消选择上一个节点(并且可能在使用ajax事件时发布新选择)。

<强>更新

我修改了Facelet和Javascript,以便在初始化时搜索树中的预选节点。请注意,必须显示预选节点才能使其正常工作。有关扩展父节点的详细信息,请参阅this answer

<强>豆:

@Named
@ViewScoped
public class BackingBean implements Serializable {

    private TreeNode rootTreeNode;

    // IMPORTANT: Use array!
    private TreeNode[] selected;

    public TreeNode getRootTreeNode() {
        if (rootTreeNode == null) {
            rootTreeNode = new DefaultTreeNode("Root", null);

            // init child tree nodes
        }
        return rootTreeNode;
    }

    public TreeNode[] getSelected() {
        return selected;
    }

    public void setSelected(TreeNode[] selected) {
        this.selected = selected;
    }

}

<强>的facelet:

<p:tree id="tree"
        onNodeClick="TREE_SELECTION.updateSelection(node, event)"
        propagateSelectionDown="false" propagateSelectionUp="false"
        selection="#{backingBean.selected}" selectionMode="checkbox"
        value="#{backingBean.rootTreeNode}"
        var="data"
        widgetVar="treeWidget">

    <p:treeNode>
        <h:outputText value="#{dataWrapper.label}" />
    </p:treeNode>

</p:tree>

<强>使用Javascript:

<script type="text/javascript">
    // singleton for tree selection
    var TREE_SELECTION = {
        init: function (treeWidgetVar) {
            this.treeWidget = PF(treeWidgetVar);
            this.selectedNode = this.treeWidget.jq.find('.ui-treenode-selected');
        },
        treeWidget: null,
        selectedNode: null,
        updateSelection: function (node, event) {
            // get the checkbox state of the clicked node
            var checkbox = node.find('> .ui-treenode-content > .ui-chkbox'),
                    checked = checkbox.find('> .ui-chkbox-box > .ui-chkbox-icon').hasClass('ui-icon-check');
            if (checked) {
                // checkbox is going to be unchecked
                this.selectedNode = null;
                return;
            }

            // check for previously selected node
            if (this.selectedNode !== null) {
                // get the checkbox of the previously selected node
                checkbox = this.selectedNode.find('> .ui-treenode-content > .ui-chkbox');

                // update tree
                this.treeWidget.uncheck(checkbox);
                this.treeWidget.removeFromSelection(this.treeWidget.getRowKey(this.selectedNode));
            }

            // cache selected node
            this.selectedNode = node;
        }
    };

    // initialize singleton when document is loaded
    $(function () {
        TREE_SELECTION.init('treeWidget');
    });
</script>