2014-02-24 193 views
2

我需要在「複選框」選擇模式下的primefaces樹,但一次只能選擇一個且只能選擇一個節點。默認情況下,當選擇節點時,primefaces樹會選擇所有的後代,而這實際上是我想要更改的。Primefaces樹複選框單選

有人能幫我弄明白嗎?

回答

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>