项目中UI需要用到树形结构显示内容,后来尽管不需要做了,不过还是自己做着玩玩,mark一下,免得以后项目中用到。
实现树形结构在此使用的是jquery的dynatree.js。关于dynatree的使用可以参考:http://wwwendt.de/tech/dynatree/doc/dynatree-doc.html#h4.2
对于树形结构,这里不做太多介绍,树一般需要一个根节点,根节点下面可以有很多子节点或者叶子节点,子结点也可以包含叶子结点或者子节点。我们在设计表结构的时候可以考虑自连接操作,实现节点之间的关联,表结构如下:
我们想要实现的数据结构如下。
对应的数据如下:
在设计树形结构的前台展示时,应该有如下信息:
- 节点名称
- 节点编号
- 当前节点对应的父节点
- 当前节点是否为叶子节点
- 当前节点是否有子节点
- 当前节点如果包含子节点情况下子节点的列表
对于程序设计,主要分成两个步骤:
- 递归将数据存储到自定义结构中;
- 对结构进行json处理,json串应该满足相关的结构,即类似JSONObject{JSONArray[...]}相关模式,可以查看上方链接了解详情。
代码如下:
1.TreeUtil:实现递归对节点关系获取以及json转换;
public without sharing class TreeUtil { // map to hold roles with Id as the key
private static Map <Id, Tree__c> treeMap; // map to hold child roles with parentRoleId as the key
private static Map <Id, List<Tree__c>> parentNodeToChildNodeMap; private static List<NodeWrapper> nodes{get;set;} private static JSONGenerator gen {get; set;} private static Tree__c rootNode{get;set;} static {
initTreeDatas();
} public static void initTreeDatas() {
treeMap = new Map<Id,Tree__c>([SELECT IsLeafNode__c, ParentNode__c, Id, Name FROM Tree__c order by ParentNode__c]);
parentNodeToChildNodeMap = new Map<Id,List<Tree__c>>();
for(Tree__c tree : treeMap.values()) {
List<Tree__c> tempList;
if(parentNodeToChildNodeMap.containsKey(tree.ParentNode__c)) {
tempList = parentNodeToChildNodeMap.get(tree.ParentNode__c);
tempList.add(tree);
parentNodeToChildNodeMap.put(tree.ParentNode__c,tempList);
} else {
tempList = new List<Tree__c>();
tempList.add(tree);
if(tree.ParentNode__c != null) {
parentNodeToChildNodeMap.put(tree.ParentNode__c,tempList);
} else {
rootNode = tree;
}
}
}
} private static void convertNodeToJSON(NodeWrapper nw){
gen.writeStartObject();
if(!nw.isLeafNode) {
gen.writeStringField('title', nw.nodeName);
gen.writeStringField('key', nw.nodeId);
gen.writeBooleanField('unselectable', false);
gen.writeBooleanField('expand', true);
gen.writeBooleanField('isFolder', true);
if (nw.hasChildNodes) {
gen.writeFieldName('children');
gen.writeStartArray();
for (NodeWrapper r : nw.childNodes) {
convertNodeToJSON(r);
}
gen.writeEndArray();
}
} else {
gen.writeStringField('title', nw.nodeName);
gen.writeStringField('key', nw.nodeId);
}
gen.writeEndObject();
} public static NodeWrapper createNode(Tree__c tree) {
NodeWrapper n = new NodeWrapper();
n.nodeName = tree.Name;
n.nodeId = tree.Id;
n.parentNodeId = tree.ParentNode__c; if(tree.IsLeafNode__c) {
n.isLeafNode = true;
n.hasChildNodes = false;
} else {
List<NodeWrapper> nwList = new List<NodeWrapper>();
if(parentNodeToChildNodeMap.get(tree.Id) != null) {
n.hasChildNodes = true;
n.isLeafNode = false;
for(Tree__c tempTree : parentNodeToChildNodeMap.get(tree.Id)) {
nwList.add(createNode(tempTree));
}
n.childNodes = nwList;
} }
return n;
} public static String getTreeAndSubTrees() {
gen = JSON.createGenerator(true);
NodeWrapper node = createNode(rootNode);
gen.writeStartArray();
convertNodeToJSON(node);
gen.writeEndArray();
return gen.getAsString();
} public class NodeWrapper { //current node name
public String nodeName{get;set;} //current node id
public String nodeId{get;set;} //if current node isn't root,set it's parent parentNodeId
public String parentNodeId{get;set;} //if this node set as a parent node,does it has child node
public Boolean hasChildNodes{get;set;} //if current node is leaf node,set to true
public Boolean isLeafNode{get;set;} //all of child nodes of current node
public List<NodeWrapper> childNodes{get;set;} public NodeWrapper() {
hasChildNodes = false;
}
} }
2.TreeController:调用TreeUtil实现数据获取
public class TreeController { public Boolean selectable {get; set;} public String selectNodeKeys {get; set;} public TreeViewController(){
selectable = false;
selectNodeKeys = 'No value selected';
} public String JsonData {get; set;} public String getJsonString() {
if (JsonData == null){
JsonData = TreeUtil.getTreeAndSubTrees();
}
return JsonData;
} }
3.TreeComponent:通过jquery的dyna tree 库实现树形结构实现
<apex:component controller="TreeController">
<apex:attribute name="selectable" type="Boolean" assignTo="{!selectable}" description=""/>
<apex:attribute name="value" type="String" description=""/>
<apex:attribute name="JsonData" type="String" assignTo="{!JsonData}" description=""/>
<apex:inputHidden id="selectedKeys" value="{!value}" />
<apex:includeScript value="{!URLFOR($Resource.DynaTree, 'jquery/jquery.js' )}" />
<apex:includeScript value="{!URLFOR($Resource.DynaTree, 'jquery/jquery-ui.custom.js' )}" />
<apex:includeScript value="{!URLFOR($Resource.DynaTree, 'jquery/jquery.cookie.js' )}" />
<apex:includeScript value="{!URLFOR($Resource.DynaTree, 'src/jquery.dynatree.js' )}" /> <apex:stylesheet value="{!URLFOR($Resource.DynaTree, 'src/skin/ui.dynatree.css')}" />
<script type="text/javascript">
$(function(){ $("#tree").dynatree({
onActivate: function(node) { },
persist: false,
checkbox: {!selectable},
generateIds: false,
classNames: {
checkbox: "dynatree-checkbox",
expanded: "dynatree-expanded"
},
selectMode: 3,
children: {!JsonString},
onSelect: function(select, node) {
var selKeys = $.map(node.tree.getSelectedNodes(), function(node){
return node.data.key;
});
jQuery(document.getElementById("{!$Component.selectedKeys}")).val(selKeys.join(", "));
var selRootNodes = node.tree.getSelectedNodes(true);
var selRootKeys = $.map(selRootNodes, function(node){
return node.data.key;
});
},
});
});
</script> <div id="tree"> </div> </apex:component>
4.TreeView.page:调用component实现显示
<apex:page controller="TreeController">
<apex:form >
<c:TreeView selectable="true"value="{!selectedValues}" />
<br/>
Value:<apex:outputText value="{!selectedValues}" />
<br/>
<apex:commandButton value="Get Value" />
</apex:form>
</apex:page>
效果展示:
总结:实现树形结构可以有多种js库选择,后台大部分需要做的就是拼json串,通过指定的要求实现前台的展示,了解树形结构如何设计更加重要。本篇只是抛砖引玉,有对树形结构感兴趣的可以将此作为参考并进行优化。内容有错误的地方欢迎指出,篇中有不懂得欢迎留言。